How to handle the unit-test assembly load issue in C# - c#

While loading assemblies from both x64/x86, I have got exception message as System.BadImageFormatException in my unit-test project.
Below is the code and screen shot of the exception I have got while debugging the test.
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Example_Addin;
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using Microsoft.Office.Interop.Visio;
using Visio = Microsoft.Office.Interop.Visio;
namespace exampleProject
{
[TestClass]
public class exampleUnitTest1
{
[TestMethod]
public void Test_example()
{
try
{
Example exm_obj = new Example();
string file_path = "test.json";
string template_file = "template.vssx";
double height = 0.5;
double width = 0.5;
db_obj.read_data_shape_creation(#file_path, 0.5, 0.5, "F06", #template_file, "testing");
}
catch (Exception)
{
System.Diagnostics.Debug.WriteLine("Exception occour");
}
}
}
Here, I want to unit test my code with assembly dependencies, but after setting the assembly, I get the above snapped exception and code execution is halted. 

This issue happen due to my target framework for unit-test and my core-project are not matching. When I have correct both case it is working.

Related

What reference should I use for 'Data.ValueRange'?

I'm following a guide to write output data from Visual Studio into a google spreadsheet.
At the end of the guide there is a code block that I pasted inside my project:
using OpenQA.Selenium.Support.UI;
using System;
using NUnit.Framework;
using OpenQA.Selenium;
using System.Collections;
using System.Collections.Generic;
using Google.Apis.Sheets.v4;
using Google.Apis.Auth.OAuth2;
using System.IO;
using Google.Apis.Services;
using Newtonsoft.Json;
using WikipediaTests.Foundation_Class;
using System.Web;
using System.Data;
using Google.Apis.Sheets.v4.Data;
namespace AutomationProjects
{
[TestFixture]
public class TestClass : TestFoundation
{
public class SpreadSheetConnector
{
//Codeblock from guide pasted here!
}
[Test]
public void test1()
{
//Test case 1. Do XYZ...
}
}
}
In the code block included in the guide there is a section about creating a list and passing data into it:
// Pass in your data as a list of a list (2-D lists are equivalent to the 2-D spreadsheet structure)
public string UpdateData(List<IList<object>> data)
{
String range = "My Tab Name!A1:Y";
string valueInputOption = "USER_ENTERED";
// The new values to apply to the spreadsheet.
List<Data.ValueRange> updateData = new List<Data.ValueRange>();
var dataValueRange = new Data.ValueRange();
dataValueRange.Range = range;
dataValueRange.Values = data;
updateData.Add(dataValueRange);
Data.BatchUpdateValuesRequest requestBody = new Data.BatchUpdateValuesRequest();
requestBody.ValueInputOption = valueInputOption;
requestBody.Data = updateData;
var request = _sheetsService.Spreadsheets.Values.BatchUpdate(requestBody, _spreadsheetId);
Data.BatchUpdateValuesResponse response = request.Execute();
// Data.BatchUpdateValuesResponse response = await request.ExecuteAsync(); // For async
return JsonConvert.SerializeObject(response);
}
The problem is that I get an error for the 'Data.ValueRange' and the 'Data.BatchUpdateValuesRequest' :
CS0246 The type or namespace name 'Data' could not be found (are you missing a using directive or an assembly reference?)
I tried adding "System.Data" as a assembly reference to my project and then added it at the top (using). But it did not remove the error.
'Data.' seems to belong to "Google.Apis.Sheets.v4" but I have already added that reference as the guide instructed.
The only fix that gets rid of the error is adding Google.Apis.Sheets.v4 before every 'Data.' like this:
List<Google.Apis.Sheets.v4.Data.ValueRange>
But when I run my tests the output does not get exported to my spreadsheet. So I'm assuming this is not the correct solution. And also I'm assuming that the guide should have included this in the code block if it was necessary.
Could there be some other reference about 'Data' I need?
According to the documentation, the ValueRange Class depends of Sheets.v4.Data, so you should add:
using Google.Apis.Sheets.v4.Data;
Also, change:
List<Data.ValueRange> updateData = new List<Data.ValueRange>();
to:
List<ValueRange> updateData = new List<ValueRange>();

C# Emgu, could not be found Capture and HaarCascade

What did I miss?
VS could not be found Capture and HaarCascade.
I added all opencv .dll and "Copy always".
And added References of Emgu.
My Emgu is emgucv-windesktop 3.2.0.2682-сuda. Visual Studio 2017
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Emgu.CV;
using Emgu.Util;
using Emgu.CV.Structure;
using Emgu.CV.CvEnum;
using System.Windows;
namespace Emgu.FaceDetection
{
public partial class Form1 : Form
{
private Capture cap;
private HaarCascade haar;
public Form1()
{
InitializeComponent();
}
}
}
You can't use HaarCascade when using EmguCV3.X, it has been deprecated and replaced with CascadeClassifier
See here for an explination, the summary being it has changed to something akin to this:
CascadeClassifier _cascadeClassifier = new CascadeClassifier(#"C:\OPENCV_3.0.0\opencv\build\etc\haarcascades\" + "haarcascade_frontalface_alt2.xml");
A more complete example, and tutorial, using 3.X can be found here, a snippet from that blog:
private CascadeClassifier _cascadeClassifier;
_cascadeClassifier = new CascadeClassifier(Application.StartupPath + "/haarcascade_frontalface_alt_tree.xml");
using (var imageFrame = _capture.QueryFrame().ToImage<Bgr, Byte>())
{
if (imageFrame != null)
{
var grayframe = imageFrame.Convert<Gray, byte>();
var faces = _cascadeClassifier.DetectMultiScale(grayframe, 1.1, 10, Size.Empty); //the actual face detection happens here
foreach (var face in faces)
{
imageFrame.Draw(face, new Bgr(Color.BurlyWood), 3); //the detected face(s) is highlighted here using a box that is drawn around it/them
}
}
imgCamUser.Image = imageFrame;
}

EmguCV "The type initializer for 'Emgu.CV.CvInvoke' threw an exception"

I have got a problem when using EmguCV. Everytime I try to create SIFT or SURF detector I get exception "The type initializer for 'Emgu.CV.CvInvoke' threw an exception".
I've already: installed MSVCRT, copied OpenCV and Emgu dlls to the execution directory, added to solution OpenCV and Emgu dlls, added to solution Emgu.CV, Emgu.CV.GPU, Emgu.CV.ML, Emgu.CV.UI, Emgu.Util references.
Unfortunately I still got exception. I've tried to build SURFFeature example and it worked perfectly. It actually means that I make some mistake, but I can't find it... Please help...
Here's the code:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Emgu.CV;
using Emgu.CV.CvEnum;
using Emgu.CV.Features2D;
using Emgu.CV.Structure;
using Emgu.CV.UI;
using Emgu.CV.Util;
using Emgu.CV.GPU;
namespace blablabla
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
Bitmap waveform_to_file = new Bitmap(2, 2);
//Emgu.CV.Features2D.SIFTDetector detector = new Emgu.CV.Features2D.SIFTDetector();//(0, 3, 0.04, 10, 1.6);//(400, true, 3, 4);//
SURFDetector surfCPU = new SURFDetector(500, false);//I got exception on these lines
Emgu.CV.Util.VectorOfKeyPoint keypoints = new Emgu.CV.Util.VectorOfKeyPoint();
Emgu.CV.Image<Emgu.CV.Structure.Gray, Byte> waveform_to_file_gray = new Emgu.CV.Image<Emgu.CV.Structure.Gray, byte>(waveform_to_file);
Emgu.CV.Features2D.ImageFeature<float>[] modKeyPointsArray = surfCPU/*detector*/.DetectFeatures(waveform_to_file_gray, null);
List<Emgu.CV.Features2D.ImageFeature<float>> modKeyPointsList = new List<Emgu.CV.Features2D.ImageFeature<float>>();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message + ex.StackTrace);
}
}
}
}
Solution explorer:
http://ifotos.pl/zobacz/4JPG_wwaerwh.jpg
bin/debug:
http://ifotos.pl/zobacz/3JPG_wwaereh.jpg

How to Call VSTS Coded Ui Scripts to QTP?

I am trying to execute my Coded UI Scripts on QTP.
First I created a dll for my Coded UI Project later I am able to access the methods from that dll but i am not able to access Coded UI testing methods.
Example:
the below script is in C# in VSTS
namespace TestProject1
{
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Input;
using System.Windows.Forms;
using System.CodeDom.Compiler;
using System.Text.RegularExpressions;
using Microsoft.VisualStudio.TestTools.UITest.Extension;
using Microsoft.VisualStudio.TestTools.UITesting;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Keyboard = Microsoft.VisualStudio.TestTools.UITesting.Keyboard;
using Mouse = Microsoft.VisualStudio.TestTools.UITesting.Mouse;
using MouseButtons = System.Windows.Forms.MouseButtons;
using Microsoft.VisualStudio.TestTools.UITesting.WinControls;
using Microsoft.VisualStudio.TestTools.UITesting.HtmlControls;
using Microsoft.VisualStudio.TestTools.UITesting.WpfControls;
public partial class UIMap
{
public int MyInteger()
{
return 9;
}
public string testDll()
{
return "Test DLL Factory";
}
public void add1()
{
MessageBox.Show("Sravan");
}
public void DeletePhoto()
{
WinWindow window = new WinWindow();
window.SearchProperties[WinWindow.PropertyNames.Name] = "Cyramed";
window.SearchProperties.Add(new PropertyExpression(WinWindow.PropertyNames.ClassName, "WindowsForms10.Window", PropertyExpressionOperator.Contains));
WinWindow c_window = new WinWindow(window);
c_window.SearchProperties[WinWindow.PropertyNames.ControlName] = "PICTUREBOX1";
c_window.WindowTitles.Add("Cyramed");
c_window.DrawHighlight();
WinClient c_client = new WinClient(c_window);
c_client.WindowTitles.Add("Cyramed");
c_client.DrawHighlight();
Mouse.Click(c_client, MouseButtons.Right);
Keyboard.SendKeys("{DOWN}");
Keyboard.SendKeys("{DOWN}");
Keyboard.SendKeys("{DOWN}");
Keyboard.SendKeys("{ENTER}");
}
}
}
I can call MyInteger and testDll methods but when I call the DeletePhoto method it throws an error: "Could not load file or assembly 'Microsoft.VisualStudio.TestTools.UITesting, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified."
My primary concern: I want to execute Coded UI scripts on QTP too.
You'll likely have to install Visual Studio Test Agents on your QTP test agents. These will drop the binaries on the machine.
VS 2010 Test Agents
VS 2010 SP1

Im getting exception Typeload what the exception can be?

I added as reference 3 dll's: Google.Apis , Google.Apis.Translate.v2 , System.Runtime.Serialization
In Form1 i have one line:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Translator.translate(new TranslateInput());
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
Now the error the exception is on the first line in the class Translator:
The line that throw the error is: var service = new TranslateService { Key = GetApiKey() };
The class code is:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Web;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using Google.Apis.Util;
using Google.Apis.Translate.v2;
using Google.Apis.Translate.v2.Data;
using TranslationsResource = Google.Apis.Translate.v2.Data.TranslationsResource;
public class Translator
{
public static string translate(TranslateInput input)
{
// Create the service.
var service = new TranslateService { Key = GetApiKey() };
string translationResult = "";
// Execute the first translation request.
Console.WriteLine("Translating to '" + input.TargetLanguage + "' ...");
TranslationsListResponse response = service.Translations.List(input.SourceText, input.TargetLanguage).Fetch();
var translations = new List<string>();
foreach (TranslationsResource translation in response.Translations)
{
translationResult = translation.TranslatedText;
}
return translationResult;
}
private static string GetApiKey()
{
return "AIzaSyCjxMe6RKHZzd7xSfSh2pEsBqUdXYm5tA8"; // Enter Your Key
}
}
/// <summary>
/// User input for this example.
/// </summary>
[Description("input")]
public class TranslateInput
{
[Description("text to translate")]
public string SourceText = "Who ate my candy?";
[Description("target language")]
public string TargetLanguage = "fr";
}
The error is:
Could not load type 'Google.Apis.Discovery.FactoryParameterV1_0' from assembly 'Google.Apis, Version=1.1.4497.35846, Culture=neutral, PublicKeyToken=null'.
Tried to google for help and also tried to change the project type to x64 platform but it didnt help. So i put it back on x86
I have windows 7 64bit visual studio c# 2010 pro .net 4.0 profile client.
Cant figure out what is the error ?
This error as reported in the above-posted messages is due to a local copy in the bin\Debug folder of your solution or project. Even though you attempt to clean your solution, such copies will persist to exist.
In order to avoid this to happen, you have to force Visual Studio to refer to the correct DLL by adding reference paths within a project properties. Unfortunately, if you got several projects within your solutions, you will have to set the reference paths for the projects one after another until completed.
Should you wish to know how to setup reference paths follow these simple instructions:
1.Select your project, right-click, then click "Properties";
2.In the project properties, click "Reference Paths";
3.Folder, type or browse to the right location of your DLL, click [Add Folder].
You will need to perform these steps for as many different locations you may have for each of your DLLs. Consider setting an output path under the Build tab of the same project properties, so that you may output your DLLs in the same directory for each of them, thus assuring you to find all the latest builds under the same location, simplifying forward your referencing.
Note this can only be one reason for this error. But it is sure that is has to do something with a wrong copy of the mentioned assembly.

Categories

Resources