Unit testing TypeInitializationException error - c#

I am working on a unit testing for a function in a form call Tester.cs, below is the error:
Error 7/31/2012 10:43:11 PM One of the background threads threw exception:
System.TypeInitializationException: The type initializer for 'Tester.Tester' threw an exception. ---> System.ArgumentNullException: Value cannot be null.
Parameter name: String
at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
at System.Int32.Parse(String s)
at Tester.Tester..cctor() in E:\Incubator\Tester\Tester\Tester.cs:line 35
--- End of inner exception stack trace ---
at Tester.Tester.Dispose(Boolean disposing)
at System.ComponentModel.Component.Finalize() MY-PC
On line 35 is a code, which basically retrieve value from configuration file and convert it to integer:
private static int _part = int.Parse(ConfigurationManager.AppSettings["Part"]);
What is the error? Thank you.

The likelyhood is that ConfigurationManager.AppSettings["Part"] is returning null. Hense the parse exception.
Does your unit test project have the app setting defined in its configuration?

You should copy your app.config (or web.config) file into test project. Otherwise test project can't find it. Remember config is related to host process, not to the dll itself.

Put the break point in line 35, something there is null which should not be...Null value can not be parsed into INT....
Be ensure that the config file is placed correctly at the directory from which you're running the application

Related

c# How do I use this function on a file

Sorry if the title may be misleading, but I have created a decoder in c#, but how do I use the function on (save.dat (the game save)) it needs to be loaded in a byte array.
Code for the decoder: https://del.dog/sorononami
Sorry I'm a starter in c#.
I have tried but I got this error:
Unhandled Exception: System.TypeInitializationException: The type initializer for 'ConsoleApp8.Program' threw an exception. ---> System.NullReferenceException: Object reference not set to an instance of an object.
at ConsoleApp8.Program.PwDecLol(Byte[] lel) in C:\repos\ConsoleApp8\ConsoleApp8\Program.cs:line 180
at ConsoleApp8.Program..cctor() in C:\repos\ConsoleApp8\ConsoleApp8\Program.cs:line 183
--- End of inner exception stack trace ---
at ConsoleApp8.Program.Main() in C:\repos\ConsoleApp8\ConsoleApp8\Program.cs:line 15
Looks like I am not doing it correctly
I don't think it's anything wrong with your decoder. The error message suggests you have a parameter in the constructor to your program, which the runtime doesn't know how to resolve.
Try removing any parameters from the main entry point into your programs (except string[] args).
Alternatively, post the code from your program's entry point.

Determine if a Patch is Installed using Microsoft.Deployment.WindowsInstaller.PatchInstallation

I thought this would be fairly straightforward but I'm having problems using the PatchInstallation class which is part of Microsoft.Deployment.WindowsInstaller.
Having obtained the correct patch code and product code (targetcode), I'm simply calling the IsInstalled property, but ArgumentNullExceptions are being thrown.
PatchInstallation patchInstallation = new PatchInstallation(patchCode.ToString("B"), productCode.ToString("B"));
return patchInstallation.IsInstalled;
Exception text is:
System.ArgumentNullException occurred Message=Value cannot be null.
Parameter name: String Source=mscorlib ParamName=String
StackTrace:
at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean
parseDecimal)
at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
at Microsoft.Deployment.WindowsInstaller.PatchInstallation.get_State()
at Microsoft.Deployment.WindowsInstaller.PatchInstallation.get_IsInstalled()
InnerException:
If anyone has any ideas what I'm doing wrong please let me know!
Cheers!
You have to choose a context before you can get a patch's state. Use the four-argument constructor that takes a UserContexts and choose one of UserManaged, UserUnmanaged, or Machine.

Correctly using stacktrace to debug

The following line of code is causing me an Exception
plug.Instance.AddDocuments(new Int32[] { val_pid }, val_ptype, val_doccat, val_subcat, val_doctype, val_notes, val_summary, SummaryAppendOptions.None, val_docStatus, new String[] { PDFFile })
And this is the exception detail.
System.Exception was caught
Message=Object reference not set to an instance of an object. - Error when trying to save document
Source=SimsBridge
StackTrace:
at SimsBridge.Bridge.AddDocuments(Int32[] personIds, Int32 PersonType, String docCatagory, Int32 subCatagory, String docType, String notes, String summary, SummaryAppendOptions summaryOptions, String documentStatusCode, String[] filePaths)
at ManagedScanDesktop.Form1.SimsScanComplete(String[] files) in C:\Working\ManagedScanDesktop 1.8\v1.8\ManagedScanDesktop\ManagedScanDesktop\Form1.cs:line 2619
InnerException:
I'm not looking for a solution to the actual exception.
My question is, does the stacktrace point to which part of the method doesn't have a reference set? Or is stacktrace just to trace to where the method is called?
The stack trace shows you the call stack when an exception is thrown. From what you've provided you can only deduce that an exception was thrown from AddDocuments. Any of the reference type parameters passed in could be null. The best way to pinpoint the problems is to set a breakpoint and than inspect the values.
Your stack trace means that either SimsBridge or SimsBridge.Bridge is null.
The message is telling you that somewhere in AddDocuments a null reference exception was thrown. It could be one of the parameters or a member.

VS 2010 error "Value to add was out of range. Parameter name: value "

I am facing a weird problem. My web application throws error "Value to add was out of range Parameter name :value ". Now this is not every time I run the program.Sometimes shows error and sometimes runs without problems (no changes done).stack traces given below the error is not clear (at least for me). Anybody faced this kind of issue ?
Error Details
Value to add was out of range.
Parameter name: value
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentOutOfRangeException: Value to add was out of range.
Parameter name: value
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[ArgumentOutOfRangeException: Value to add was out of range.
Parameter name: value]
System.DateTime.Add(Double value, Int32 scale) +9388319
System.Web.Compilation.CodeDirectoryCompiler.GetCodeDirectoryAssembly(VirtualPath virtualDir, CodeDirectoryType dirType, String assemblyName, StringSet excludedSubdirectories, Boolean isDirectoryAllowed) +8837703
System.Web.Compilation.BuildManager.CompileCodeDirectory(VirtualPath virtualDir, CodeDirectoryType dirType, String assemblyName, StringSet excludedSubdirectories) +125
System.Web.Compilation.BuildManager.CompileCodeDirectories() +319
System.Web.Compilation.BuildManager.EnsureTopLevelFilesCompiled() +248
[HttpException (0x80004005): Value to add was out of range.
Parameter name: value]
System.Web.Compilation.BuildManager.ReportTopLevelCompilationException() +62
System.Web.Compilation.BuildManager.EnsureTopLevelFilesCompiled() +421
System.Web.Compilation.BuildManager.CallAppInitializeMethod() +31
System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +605
[HttpException (0x80004005): Value to add was out of range.
Parameter name: value]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9013676
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +97
System.Web.HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr) +258
--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.1
Just guesses: as the exception seems to be thrown from the code that you do not control, it is not your code that causes the error. However, that could be your system settings. For example, for some weird reason System.DateTime.Add(Double value, Int32 scale) is called with such parameters, that, as MSDN states,
The resulting DateTime is less than MinValue or greater than MaxValue.
Is it ever possible that the time on your computer is now set to some incredibly high value? Close to 23:59:59.9999999, December 31, 9999, for instance. Or maybe low value, close to 00:00:00.0000000, January 1, 0001. So the compiler for some reasons picks up the current date and needs to add some time span to it, which causes your error.
Just a wild guess, but maybe...
UPDATE
The code of the System.Web.Compilation.CodeDirectoryCompiler.GetCodeDirectoryAssembly method can be found here. In the code there is a line
DateTime waitLimit = DateTime.UtcNow.AddMilliseconds(3000);
That's the only place that could throw such exception (if the version I am looking at is the same as your environment). So it gives more votes for weird time set on your computer.
This can happen if the value you are trying to assign is null. Try coalescing the value
suppose:
int i = value ?? 0; //if value is null, zero is assigned to i
MyClass _class = ValueClass ?? new MyClass(); //same as above, except it instantiates.
DateTime someDate = getChuckNorrisBirthDate() ?? DateTime.Now.Date(); // beware of chuck norris
I have seen this error with DateTime variables.. but it was ages ago. Since you do not provide enough information about the type of variable etc (and the image is too small to make out anything) I am just guessing it on top of my head.
Issue solved. Just changed my regional settings,date/time settings in control panel to some random setting and then reverted them back to original followed by a PC restart and error is gone.Issue might be with the GetCodeDirectoryAssembly code as mentioned by #Michael Sagalovich.Will investigate for more details if the error pops up again :)
Thanks All

problem breaking up one SharePoint project into pieces

I'm trying to break my sharepoint project into a few smaller projects.
I could easily move utility files in different project.
However i encountered a problem when i moved custom-fields.
If i move custom-field from ProjectA to ProjectB and set ProjectA to reference ProjectB's DLL, building and deploying work fine. However, when program reference custom-field from SPListItem, it will throw System.ArgumentOutOfRangeException.
e.g.
SPListItem item = splist.GetItemById(id);<br>
CustomFieldValue custom = item["Custom"] // Error occurs here
Also, if i call AddFieldAsXml to define above custom-field, i get same error.
can anyone help me solve this problem?
thank you in advance...
Detail of Error occured in AddFieldAsXml (same error occurs when referencing)
Length cannot be less than zero.
Parameter name: length
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentOutOfRangeException: Length cannot be less than zero.
Parameter name: length
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[ArgumentOutOfRangeException: Length cannot be less than zero.
Parameter name: length]
System.String.InternalSubStringWithChecks(Int32 startIndex, Int32 length, Boolean fAlwaysCopy) +7494967
System.String.Substring(Int32 startIndex, Int32 length) +11
Microsoft.SharePoint.Publishing.PublishingHttpModule.CreateSPField(String fieldTypeName, SPFieldCollection collection, String fieldName) +80
Microsoft.SharePoint.SPFieldCollection.CreateSPField(Int32 index) +2746
Microsoft.SharePoint.SPFieldCollection.EnsureSPField(Int32 index) +89
Microsoft.SharePoint.SPFieldCollection.get_Item(Int32 iIndex) +113
Microsoft.SharePoint.SPFieldCollection.GetFieldByInternalName(String strName, Boolean bThrowException) +180
Microsoft.SharePoint.SPFieldCollection.GetFieldByInternalName(String strName) +38
Microsoft.SharePoint.SPFieldCollection.AddFieldAsXmlInternal(String schemaXml, Boolean addToDefaultView, SPAddFieldOptions op) +905
Microsoft.SharePoint.SPFieldCollection.AddFieldAsXml(String schemaXml, Boolean addToDefaultView, SPAddFieldOptions op) +45
This error displayed if string.substring(int startIndex, int length)'s length value is minus...
but i don't know why i get this error.
I solved the problem...
I didn't copy the fldtypes_xxxx.xml information.
so when the code try to read some information from the xml, exception is thrown...

Categories