Ranorex fails to run, system.TypeInitializationException

Bug reports.
jt1
Posts: 16
Joined: Fri Sep 25, 2015 4:18 pm

Ranorex fails to run, system.TypeInitializationException

Post by jt1 » Tue Jun 07, 2016 1:26 pm

Hello,

I recently started having a problem with the Ranorex.Core.dll. Whenever a test case is run, a runtime error occurs immediately.
systemInitializationError.PNG
When run with the debugger it is clear the code does not run any lines, it crashes as soon as it starts. I have tried reinstalling Ranorex with no success. I first noticed this problem after zipping up a copy of the solution, although I don't see a reason this would have an affect. I did not leave the zip file in the solution folder.

I am running
Ranorex 6.0.0
.Net Runtime 4.0.30319.42000

Any advice is appreciated, thank you!
You do not have the required permissions to view the files attached to this post.

User avatar
odklizec
Ranorex Guru
Ranorex Guru
Posts: 7470
Joined: Mon Aug 13, 2012 9:54 am
Location: Zilina, Slovakia

Re: Ranorex fails to run, system.TypeInitializationException

Post by odklizec » Tue Jun 07, 2016 1:52 pm

Hi,

This is unfortunately a known 6.0 debugger issue (already reported to Ranorex and reproduced).

The workaround (until it gets fixed) is to go menu Tools >> Options >> Debugging and here uncheck option “Pause on handled exceptions” option. Ranorex should stop throwing this kind of exceptions during debugging and you should still be able to debug your own code.
Pavel Kudrys
Ranorex explorer at Descartes Systems

Please add these details to your questions:
  • Ranorex Snapshot. Learn how to create one >here<
  • Ranorex xPath of problematic element(s)
  • Ranorex version
  • OS version
  • HW configuration

jt1
Posts: 16
Joined: Fri Sep 25, 2015 4:18 pm

Re: Ranorex fails to run, system.TypeInitializationException

Post by jt1 » Tue Jun 07, 2016 2:19 pm

Thank you for replying so quickly. I went to the options but the "Pause on handled Exceptions" was already off. I tried it turned on, nothing changed. Just to be clear, I am seeing this not just while debugging, it happens no matter how I try to run the code.
Is there any more information I could give you to help figure this out?

krstcs
Posts: 2683
Joined: Tue Feb 07, 2012 4:14 pm
Location: Austin, Texas, USA

Re: Ranorex fails to run, system.TypeInitializationException

Post by krstcs » Tue Jun 07, 2016 2:23 pm

It appears that he is using Visual Studio for development/debugging, not Ranorex Studio. Does the Ranorex issue still apply here? Is the issue one that is in Ranorex.Core.dll and therefore ANY debugger will have this issue, or is it a problem specifically with the Ranorex Studio debugger integration?

Also, in 6.0, Ranorex Studio defaults to running WITHOUT the debugger attached, but VS doesn't. Jt1, have you tried running without the debugger in VS?
Shortcuts usually aren't...

jt1
Posts: 16
Joined: Fri Sep 25, 2015 4:18 pm

Re: Ranorex fails to run, system.TypeInitializationException

Post by jt1 » Tue Jun 07, 2016 2:39 pm

I have tried release and debug mode in both VS and Ranorex. The error doesn't change, although in Ranorex the report doesn't say TypeInitialzationError:
ranorexError.PNG
I'm thinking of replacing the Ranorex.Core.dll file on my machine with a coworker's copy to see if that makes a difference.
You do not have the required permissions to view the files attached to this post.

krstcs
Posts: 2683
Joined: Tue Feb 07, 2012 4:14 pm
Location: Austin, Texas, USA

Re: Ranorex fails to run, system.TypeInitializationException

Post by krstcs » Tue Jun 07, 2016 2:43 pm

Have you tried a clean reinstall of Ranorex?

1. Uninstall Ranorex.
2. Reboot.
3. Re-install Ranorex (Ranorex-6.0.0.exe)

Also, are you having any issues with any other .NET applications?
Shortcuts usually aren't...

krstcs
Posts: 2683
Joined: Tue Feb 07, 2012 4:14 pm
Location: Austin, Texas, USA

Re: Ranorex fails to run, system.TypeInitializationException

Post by krstcs » Tue Jun 07, 2016 2:44 pm

Also, your error seems to be saying that you are passing a null value to the maillogger initialization. Have you checked to make sure that you are calling the constructor correctly?


Edit to add:

Also, can you post the FULL code of your Program.cs file? My guess is that you are trying to instantiate the mail logger before the call to test suite runner. Without seeing the code though, it is hard to know for sure.

2nd edit:

In addition, Global Parameters are initialized by the test suite runner, so you won't have access to them in Main unless you parse the command-line parameters yourself. My guess is that you are trying to pass in the to/from info as global params, and since they aren't initialized yet, they are null, so you are passing a null reference to the mail constructor.
Shortcuts usually aren't...

User avatar
odklizec
Ranorex Guru
Ranorex Guru
Posts: 7470
Joined: Mon Aug 13, 2012 9:54 am
Location: Zilina, Slovakia

Re: Ranorex fails to run, system.TypeInitializationException

Post by odklizec » Tue Jun 07, 2016 2:52 pm

Well, I'm not using VS, but I would guess that "Pause on handled exceptions" is Ranorex-only related? I tried to reproduce it with SharpDevelop 4.4, using Ranorex.Core.dll but here it compiled and debugged OK. Plus it has something to do with project settings. Ranorex folks were not able to reproduce it until they saw screenshot of my project >> Compiling settings. Unfortunately, I did not ask, which particular project setting is causing this issue.
Pavel Kudrys
Ranorex explorer at Descartes Systems

Please add these details to your questions:
  • Ranorex Snapshot. Learn how to create one >here<
  • Ranorex xPath of problematic element(s)
  • Ranorex version
  • OS version
  • HW configuration

jt1
Posts: 16
Joined: Fri Sep 25, 2015 4:18 pm

Re: Ranorex fails to run, system.TypeInitializationException

Post by jt1 » Tue Jun 07, 2016 3:03 pm

I have tried a clean install and reboot, didn't make a difference.
This code hasn't been touched in over 200 days and never had any errors before, which is why I think the problem is something else. The error happens before the first line of code is reached in VS, naturally it would occur in Main.

Code: Select all

using System;
using System.Threading;
using System.Drawing;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using WinForms = System.Windows.Forms;
using DVRex_Automation.Classes.External_Classes.MailLogger;

using Ranorex;
using Ranorex.Core;
using Ranorex.Core.Reporting;
using Ranorex.Core.Testing;

namespace DVRex_Automation
{
    class Program
    {
        [STAThread]
        public static int Main(string[] args)
        {
            // Uncomment the following 2 lines if you want to automate Windows apps
            // by starting the test executable directly
            //if (Util.IsRestartRequiredForWinAppAccess)
            //    return Util.RestartWithUiAccess();

            Keyboard.AbortKey = System.Windows.Forms.Keys.Pause;
            int error = 0;

            MailLogger mailLogger = null;
            
            try
            {
				mailLogger = new MailLogger("DVRex Regression Report");
				MailLogger.ReportLevelMail = ReportLevel.Success;
				Report.AttachLogger(mailLogger);
            	
                error = TestSuiteRunner.Run(typeof(Program), Environment.CommandLine);
            }
            catch (Exception e)
            {
                Report.Error("Unexpected exception occurred: " + e.ToString());
                error = -1;
            }
            Report.End();
			
			if (mailLogger != null)
					mailLogger.PrepareAndSendMail();
            return error;
        }
    }
}
EDIT: My compilation settings
compileRanorex.PNG
You do not have the required permissions to view the files attached to this post.

krstcs
Posts: 2683
Joined: Tue Feb 07, 2012 4:14 pm
Location: Austin, Texas, USA

Re: Ranorex fails to run, system.TypeInitializationException

Post by krstcs » Tue Jun 07, 2016 3:29 pm

My guess is that the MailLogger class has changed. The error specifically says the constuctor needs 2 parameters (string from, string to), but you are only passing 1 (which appears to be a subject line instead of a from/to email address).

Check the library/call and make sure your implementation is still correct.

Edit for grammar...
Shortcuts usually aren't...

jt1
Posts: 16
Joined: Fri Sep 25, 2015 4:18 pm

Re: Ranorex fails to run, system.TypeInitializationException

Post by jt1 » Tue Jun 07, 2016 4:28 pm

I had a coworker go through the debugger step by step while I watched the MailLogger hit the proper constructor with no errors. My machine is the only one with problems. When I comment out all references to MailLogger the code works in Ranorex but in VS the system.TypeInitializationException still happens. So while it is clear MailLogger now appears to have an issue, MailLogger hasn't changed and works for other people.
There are differences in how VS and Ranorex are breaking, it is not clear to me whether how related these problems are.
This is the MailLogger class for reference, the constructor first so you don't have to dig for it.

Code: Select all

		public MailLogger(string subject)
		{
			string from = ConfigurationManager.AppSettings.Get("FromEmail");
			string to = ConfigurationManager.AppSettings.Get("ToEmail");
			mail = new MailMessage(from, to);
			mail.Subject = subject;
		}

Code: Select all


using System;
using System.Collections.Generic;
using System.Drawing;
using System.Net.Mail;
using System.Net.Mime;
using Ranorex;
using Ranorex.Core;
using System.Configuration;

namespace DVRex_Automation.Classes.External_Classes.MailLogger
{

	public class MailLogger : IReportLogger
	{
		private static string host = "***";
		private static int port = 25;
		private static ReportLevel reportlevel = ReportLevel.Debug;

		public static string Host
		{
			get { return host; }
			set { host = value; }
		}

		public static int Port
		{
			get { return port; }
			set { port = value; }
		}
		
		public static ReportLevel ReportLevelMail
		{
			get { return reportlevel; }
			set {reportlevel = value;}
		}

		#region CSS style
		const string CssStyle = @"<style type=""text/css"">

          html,body
          {
          color: black; 	background-color: #ebebeb;

          font-size: 1em;
          font-family: Verdana;

          margin: 0; padding: 0;
          text-align: center;
          }

          body, html, div, p, i, strong, table {color:#606060; }
          img{border:0px;}
          div#Content img { margin: 7px 0;}

          p,i
          {
          margin: 0;
          padding: 3px 0px;
          }

          div#Content table
          {
          font-size: 1em;
          margin: 2px;
          }

		  table
		  {
			background-color: #fff;
		  }

          table td
          {
          padding: 3px 4px;
          margin: 0;
          }


          a:link
          {
          color: #c11111;
          }
          a:visited
          {
          color: #db4848;

          }
          a:active
          {
          color: #c11111;

          }
          a:hover
          {
          color: black;

          }

          h1
          {
          font-size: 13pt;
          }
          
          h2
          {
          font-size: 12pt;
          }

          th
          {
          background-color: #eee;
          text-align: left;
          padding: 10px 4px;
          }

          td
          {
          border-bottom: 1px solid #eee;
          padding: 0;
          }

          fieldset
          {
          clear: both;
          font-size: 100%;
          border-color: #000000;
          border-width: 0;
          border-style: solid none none none;
          padding: 5px;
          margin: 3px 2px 10px 2px;
          }

          fieldset legend
          {
          font-size:	10pt;
          color: #555;
          font-weight: bold;
          margin: 0 0 0 -7px;
          padding: 10px 0 0 0;
          }
          label
          {
          float: left;
          text-align: right;
          width: auto;
          margin-right: 0em;
          padding: 2px 0;
          }

        </style>";
		#endregion

		private MailMessage mail;
		private bool success = true;

		// html mail
		private string htmlText = string.Empty;
		private List<LinkedResource> linkedResources = new List<LinkedResource>();
		private int cid = 1;

		public MailLogger(string subject)
		{
			string from = ConfigurationManager.AppSettings.Get("FromEmail");
			string to = ConfigurationManager.AppSettings.Get("ToEmail");
			mail = new MailMessage(from, to);
			mail.Subject = subject;
		}

		public bool PreFilterMessages
		{
			get { return true; }
		}

		public void Start()
		{
			// nothing to do here
		}

		public void End()
		{
			// evaluate the success flag
			mail.Body = "Summary: " + (success ? "PASSED" : "FAILED") + "\n\n" + mail.Body;

			htmlText = "<body>" + CssStyle +
				"<h1>DVRex Report</h1>" +
				"<h2>Summary: " + (success ? "PASSED" : "FAILED") + "</h2>" +
				@"<table>
					<tr>
						<th width=""15%""><b>Time</b></th>
						<th width=""10%""><b>Level</b></th>
						<th width=""15%""><b>Category</b></th>
						<th><b>Message</b></th>
					</tr>"
				+ htmlText + "</table></body>";

			// add html email part
			AlternateView htmlPlainView = AlternateView.CreateAlternateViewFromString(
				htmlText, null, MediaTypeNames.Text.Html);
			foreach (LinkedResource res in linkedResources)
				htmlPlainView.LinkedResources.Add(res);
			mail.AlternateViews.Add(htmlPlainView);		
		}
		
		public void PrepareAndSendMail(){
			
			try
			{			
				Ranorex.Core.Reporting.TestReport.SaveReport();
				
				// Zipped Report file
				String fileName = Ranorex.Core.Reporting.TestReport.ReportFilename;
				
				String zipFileName = fileName.Replace("rxlog","rxzlog");
				if (System.IO.File.Exists(zipFileName))
				{
					System.Net.Mail.Attachment MyReport = new System.Net.Mail.Attachment(zipFileName);
					mail.Attachments.Add (MyReport);
				}
				
				//enter network credentials
				System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient("***");
				System.Net.NetworkCredential basicCredential = new System.Net.NetworkCredential ("***", "***");
					
				client.Credentials = basicCredential;
				client.Send(mail);
			}
			catch (Exception ex)
			{
				Console.WriteLine(ex);
			}
		}

		public void LogText(ReportLevel level, string category, string message, bool escape)
		{
			LogText(level, category, message, escape, new Dictionary<string, string>());
		}

		public void LogText(ReportLevel level, string category, string message, bool escape, IDictionary<string, string> metaInfos)
		{
			 if (ReportLevelMail.Level <= level.Level) {
				CheckSuccess(level);
				mail.Body += string.Format("[{0}][{1, -7}][{2}]: {3}\n", GetTimeStamp(),
				                           level, category, message);
	
				string htmlMessage = escape ? System.Web.HttpUtility.HtmlEncode(message) : message;
				htmlText += String.Format("<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td></tr>",
				                          GetTimeStamp(), level.ToString().ToUpper(), category, htmlMessage);
			}
		}

		public void LogData(ReportLevel level, string category, object data)
		{
			LogData(level, category, "Data logged.", data, new Dictionary<string, string>());
		}

		public void LogData(ReportLevel level, string category, string message, object data, IDictionary<string, string> metaInfos)
		{
			string dataMessage;
			// special handling of Bitmap data
			if (data is Bitmap)
			{
				Bitmap bitmap = (Bitmap)data;
				// add special code to store bitmaps here -> add image to HTML email
				string cidString = AddBitmapToLinkedResources(bitmap);
				dataMessage = String.Format(
					@"<a href=""{0}""><img width=""300"" src=""{1}"" alt=""{2}""/></a>",
					"cid:" + cidString, "cid:" + cidString, message);
			}
			else
			{
				dataMessage = (data != null) ? data.GetType().ToString() : "(null)";
			}

			LogText(level, category, dataMessage, false, metaInfos);
		}

		private void CheckSuccess(ReportLevel level)
		{
			if (level == ReportLevel.Error || level == ReportLevel.Failure)
				success = false;
		}

		private string GetTimeStamp()
		{
			return System.DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.fff",
			                                    System.Globalization.CultureInfo.InvariantCulture);
		}

		private string AddBitmapToLinkedResources(Bitmap bitmap)
		{
			string cidString = "ID_" + cid++;
			AddBitmapToLinkedResources(bitmap, cidString);
			return cidString;
		}

		private void AddBitmapToLinkedResources(Bitmap bitmap, string cidString)
		{
			System.IO.MemoryStream stream = new System.IO.MemoryStream();
			bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
			stream.Seek(0, System.IO.SeekOrigin.Begin);

			LinkedResource imageResource = new LinkedResource(stream, MediaTypeNames.Image.Jpeg);
			imageResource.ContentId = cidString;
			imageResource.TransferEncoding = TransferEncoding.Base64;
			linkedResources.Add(imageResource);
		}
	}
}


krstcs
Posts: 2683
Joined: Tue Feb 07, 2012 4:14 pm
Location: Austin, Texas, USA

Re: Ranorex fails to run, system.TypeInitializationException

Post by krstcs » Tue Jun 07, 2016 4:38 pm

Are you sure the appsettings FromEmail and ToEmail fields are set correctly on your system?

It appears that the call to ConfigurationManager.AppSettings.Get("FromEmail") is returning null, which is then used in the call to 'new MailMessage(from, to);' 2 lines later.

My guess is that the configuration is not saved on your system correctly (or at all?)...
Shortcuts usually aren't...

jt1
Posts: 16
Joined: Fri Sep 25, 2015 4:18 pm

Re: Ranorex fails to run, system.TypeInitializationException

Post by jt1 » Tue Jun 07, 2016 4:46 pm

The app file is in the project and the values are not null. I recently deleted everything on my machine and got a fresh copy of latest in an effort to solve this problem.

My next step will be replacing the Ranorex.Core.dll with a coworker's who isn't having problems. If that doesn't do it I will reinstall Ranorex and VS. and If that doesn't work I will cry :(

krstcs
Posts: 2683
Joined: Tue Feb 07, 2012 4:14 pm
Location: Austin, Texas, USA

Re: Ranorex fails to run, system.TypeInitializationException

Post by krstcs » Tue Jun 07, 2016 6:01 pm

Try adding some debugging code (Console.Writeline(from);, etc.) around the calls in your MailLogger class, or add break points and run in debug mode. That seems to be where the issue is. Try to find out what actual value is being thrown into the from string.

If it's happening in Ranorex and VS, then it's probably not a Ranorex issue though. Even though the error is different, I think the problem is the same.
Shortcuts usually aren't...

User avatar
odklizec
Ranorex Guru
Ranorex Guru
Posts: 7470
Joined: Mon Aug 13, 2012 9:54 am
Location: Zilina, Slovakia

Re: Ranorex fails to run, system.TypeInitializationException

Post by odklizec » Tue Jun 07, 2016 6:40 pm

What else you can try (in Ranorex Studio) is to go to Tools >> Options >> Debugging and here uncheck Debug just my code option. Then try to debug your projects in Ranorex Studio. If it's a problem I've experienced, then I'm sure it will fail somewhere after that Keys.Pause line.
Pavel Kudrys
Ranorex explorer at Descartes Systems

Please add these details to your questions:
  • Ranorex Snapshot. Learn how to create one >here<
  • Ranorex xPath of problematic element(s)
  • Ranorex version
  • OS version
  • HW configuration