How can I take screenshots for different steps performing in execution of an automated test for android/iOS mobile in C# language?
There appear to be numerous suggestions on how to do this.
This is one places code in OnCreateView():
public static Android.Content.Context Context { get; private set; }
public override View OnCreateView(View parent, string name, Context context, IAttributeSet attrs)
{
MainActivityContext = context;
return base.OnCreateView(parent, name, context, attrs);
}`
Then, I wrote a service implemenatation in which I take a screen capture, by using the static Context of the MainActivity, like this :
`public class SnapshotService : ISnapshotService
{
public void Capture()
{
var screenshotPath =
Android.OS.Environment.GetExternalStoragePublicDirectory("Pictures").AbsolutePath +
Java.IO.File.Separator +
"screenshot.png";
var rootView = ((Android.App.Activity)MainActivity.Context).Window.DecorView.RootView;
using (var screenshot = Android.Graphics.Bitmap.CreateBitmap(
rootView.Width,
rootView.Height,
Android.Graphics.Bitmap.Config.Argb8888))
{
var canvas = new Android.Graphics.Canvas(screenshot);
rootView.Draw(canvas);
using (var screenshotOutputStream = new System.IO.FileStream(
screenshotPath,
System.IO.FileMode.Create))
{
screenshot.Compress(Android.Graphics.Bitmap.CompressFormat.Png, 90, screenshotOutputStream);
screenshotOutputStream.Flush();
screenshotOutputStream.Close();
}
}
}
}`
C#
You can use this piece of code:
ScenarioContext.Current.Get<IApp>("Application").Screenshot(ScenarioStepContext.Current.StepInfo.Text);
Related
Pretty much what it says in the title.
I've built a second .dll file which contains my Content Importer/Processor and added that .dll file in my 'References' section for my Content Manager for my project, but nothing. The Manager doesn't detect my custom importer/processor. No idea what's going on and I wasn't able to find anyone else having an issue like this, so I was hoping someone more experienced could help me out here!
I am using Json.NET for the Json Deserialization by the way.
Thank you in advence :)
MapJson Code:
public class MapJson
{
[JsonProperty("name")]
public String Name = "";
[JsonProperty("width")]
public Int32 MapWidth = 0;
[JsonProperty("height")]
public Int32 MapHeight = 0;
}
Importer Code:
[ContentImporter(".amap", DefaultProcessor = "MapProcessor", DisplayName = "Map Importer - Engine")]
public class MapImporter : ContentImporter<MapJson>
{
public override MapJsonImport(string filename, ContentImporterContext context)
{
string json = new FileHandle(filename).ReadAll();
MapJson data = JsonConvert.DeserializeObject<MapJson>(json);
return data;
}
}
Processor Code:
[ContentProcessor(DisplayName = "Map Processor - Engine")]
public class MapProcessor : ContentProcessor<MapJson, MapJson>
{
public override MapJson Process(MapJson input, ContentProcessorContext context)
{
return input;
}
}
Writer Code:
[ContentTypeWriter]
public class MapWriter : ContentTypeWriter<MapJson>
{
protected override void Write(ContentWriter writer, MapJson value)
{
writer.Write(value.Name);
writer.Write(value.MapWidth);
writer.Write(value.MapHeight);
}
}
Reader Code:
public class MapReader : ContentTypeReader<Map>
{
protected override Map Read(ContentReader reader, Map existingInstance)
{
MapJson data = new MapJson();
data.Name = reader.ReadString();
data.MapWidth = reader.ReadInt32();
data.MapHeight = reader.ReadInt32();
// this constructor just sets my 'Map' class's Name, MapWidth and MapHeight variables
return new Map(data);
}
}
Well uhh this is embarrassing...
The solution was to first build the game project, then to actually re-build the content importer/processor project, and then to link it with the content manager!
I feel so stupid haha
I am trying to pass a camera overlay function as a dependency service into my shared code using the Media Plugin for Xamarin https://github.com/jamesmontemagno/MediaPlugin.
I can not figure out how to implement the dependency service correctly. The app runs but when I open the camera, it doesn't display the overlay. If someone could help me with my code, or direct me to an example of using the overlay option, I would really appreciate it.
My interface code:
public interface IPhotoOverlay
{
object GetImageOverlayAsync();
}
My iOS code:
public object GetImageOverlayAsync()
{
Func<object> func = CreateOverlay;
return func;
}
public object CreateOverlay()
{
var imageView = new UIImageView(UIImage.FromBundle("face-template.png"));
imageView.ContentMode = UIViewContentMode.ScaleAspectFit;
var screen = UIScreen.MainScreen.Bounds;
imageView.Frame = screen;
return imageView;
}
My shared code:
var photo = await Plugin.Media.CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions() {
OverlayViewProvider = DependencyService.Get<IPhotoOverlay>().GetImageOverlayAsync,
DefaultCamera = Plugin.Media.Abstractions.CameraDevice.Front});
In your Xamarin.iOS Service, you need to register the Dependency, here is an example.
[assembly: Dependency (typeof (PhotoOverlayiOS))]
namespace UsingDependencyService.iOS
{
public class PhotoOverlayiOS : IPhotoOverlay
{
public object GetImageOverlayAsync()
{
Func<object> func = CreateOverlay;
return func;
}
public object CreateOverlay()
{
var imageView = new UIImageView(UIImage.FromBundle("face-template.png"));
imageView.ContentMode = UIViewContentMode.ScaleAspectFit;
var screen = UIScreen.MainScreen.Bounds;
imageView.Frame = screen;
return imageView;
}
}
}
I'm trying to write a command line tool that modifies some code using Roslyn. Everything seems to go well: the solution is opened, the solution is changed, the Workspace.TryApplyChanges method returns true. However no actual files are changed on disk. What's up? Below is the top level code I'm using.
static void Main(string[] args)
{
var solutionPath = args[0];
UpdateAnnotations(solutionPath).Wait();
}
static async Task<bool> UpdateAnnotations(string solutionPath)
{
using (var workspace = MSBuildWorkspace.Create())
{
var solution = await workspace.OpenSolutionAsync(solutionPath);
var newSolution = await SolutionAttributeUpdater.UpdateAttributes(solution);
var result = workspace.TryApplyChanges(newSolution);
Console.WriteLine(result);
return result;
}
}
I constructed a short program using your code and received the results I expected - the problem appears to reside within the SolutionAttributeUpdater.UpdateAttributes method. I received these results using the following implementation with your base main and UpdateAnnotations-methods:
public class SolutionAttributeUpdater
{
public static async Task<Solution> UpdateAttributes(Solution solution)
{
foreach (var project in solution.Projects)
{
foreach (var document in project.Documents)
{
var syntaxTree = await document.GetSyntaxTreeAsync();
var root = syntaxTree.GetRoot();
var descentants = root.DescendantNodes().Where(curr => curr is AttributeListSyntax).ToList();
if (descentants.Any())
{
var attributeList = SyntaxFactory.AttributeList(
SyntaxFactory.SingletonSeparatedList(
SyntaxFactory.Attribute(SyntaxFactory.IdentifierName("Cookies"), SyntaxFactory.AttributeArgumentList(SyntaxFactory.SeparatedList(new[] { SyntaxFactory.AttributeArgument(
SyntaxFactory.LiteralExpression(
SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(#"Sample"))
)})))));
root = root.ReplaceNodes(descentants, (node, n2) => attributeList);
solution = solution.WithDocumentSyntaxRoot(document.Id, root);
}
}
}
return solution;
}
}
It was tested using the following class in the sample solution:
public class SampleClass<T>
{
[DataMember("Id")]
public int Property { get; set; }
[DataMember("Id")]
public void DoStuff()
{
DoStuff();
}
}
And it resulted in the following Output:
public class SampleClass<T>
{
[Cookies("Sample")] public int Property { get; set; }
[Cookies("Sample")] public void DoStuff()
{
DoStuff();
}
}
If you take a look at the UpdateAttributes method I had to replace the nodes with ReplaceNodes and updated the solution by calling WithDocumentSyntaxRoot.
I would assume that either one of those two calls is missing or that nothing was changed at all - if you call workspace.TryApplyChanges(solution) you would still receive true as an Output.
Note that using multiple calls of root.ReplaceNode() instead of root.ReplaceNodes() can also result in an error since only the first update is actually used for the modified document - which might lead you to believe that nothing has changed at all, depending on the implementation.
I am trying to build a small operating system using c# and Cosmos
At fisrt this went pretty good only from one moment to the other it stoped working and gave me the following error:
Error occurred while invoking NAsm.
OSBoot.asm Line: 241424 Code: push dword System_Void__System_IO_Stream_Dispose__
OSBoot.asm Line: 242633 Code: push dword System_Void__System_IO_Stream_Dispose__ t
OSBoot.asm Line: 247640 Code: push dword System_Void__System_IO_Stream_Dispose__
OSBoot.asm Line: 248618 Code: push dword System_Void__System_Collections_Generic_List_1_Enumerator__Commands_ICommand_ICommandBase_Dispose_
I even installed a new installation of Microsoft Visual studio with cosmos on a new system and started over from scratch, at first it worked but asgain withoud any chage it stopped working
using System;
using Commands;
using Sys = Cosmos.System;
namespace OS
{
public class Kernel : Sys.Kernel
{
private Env SysEnv { get; set; }
private InputHandeler InputHandler { get; set; }
protected override void BeforeRun()
{
Console.WriteLine("Creating Enviriment...");
SysEnv = new Env();
InputHandler = new InputHandeler(new CommandLister());
Console.WriteLine("Enviriment build");
Console.Clear();
Console.WriteLine("Os booted successfully.");
}
protected override void Run()
{
Console.Write(SysEnv.ConsolCommandPrefix);
var input = Console.ReadLine();
try
{
InputHandler.ExecuteInput(input);
} catch(Exception)
{
//TODO good exeption and the use of it
}
}
}
}
Env class
namespace OS
{
public class Env
{
public string CurrentUser { get; set; }
public string CurrnetDir { get; set; }
private string prefix;
public string ConsolCommandPrefix
{
get { return CurrentUser + "#" + CurrnetDir + prefix; }
set { prefix = value; }
}
public Env()
{
ConsolCommandPrefix = "> ";
CurrentUser = "Admin";
CurrnetDir = "/";
}
}
}
CommandLister class
using System;
using System.Collections.Generic;
using Commands.Command;
using Commands.Command.SystemCommands;
using Commands.ICommand;
namespace Commands
{
public class CommandLister
{
private List<ICommandBase> KnownCommands { get; set; }
private Unkown UnkownCommand { get; set; }
public CommandLister()
{
KnownCommands = new List<ICommandBase>();
addCommand(new Help());
UnkownCommand = new Unkown();
}
public void addCommand(ICommandBase command)
{
KnownCommands.Add(command);
}
public ICommandBase getCommand(String input)
{
foreach (var command in KnownCommands)
{
if(true)
{
return command;
}
}
return UnkownCommand;
}
}
}
The other classes only contain some text and only print something to the Console
I have two questions:
- What is causing this
- How can i solve this problem
Edit: i tried it again ron an other OS (i used vista the first time), this time i used Windows 7. The same thing happend at first it worked (i started from scratch again..) but after a few builds and runs it somehow broke again. even when undoing the changes i made. it wont build anymore.
Kind regards,
Edo Post
I have a code in VB6. Can anyone tell me how to write it in C#. This code is below:
Set Amibroker = CreateObject("Broker.Application")
Set STOCK = Amibroker.Stocks.Add(ticker)
Set quote = STOCK.Quotations.Add(stInDate)
quote.Open = stInOpen
quote.High = stInHigh
quote.Low = stInlow
quote.Close = stInYcp
quote.Volume = stInVolume
Set STOCK = Nothing
Set quote = Nothing
What is the equivalent of CreateObject in C#?. I try to add references to com object but i can't find any com object as Broker.Application or amibroker
If you are using .net 4 or later, and therefore can make use of dynamic, you can do this quite simply. Here's an example that uses the Excel automation interface.
Type ExcelType = Type.GetTypeFromProgID("Excel.Application");
dynamic ExcelInst = Activator.CreateInstance(ExcelType);
ExcelInst.Visible = true;
If you can't use dynamic then it's much more messy.
Type ExcelType = Type.GetTypeFromProgID("Excel.Application");
object ExcelInst = Activator.CreateInstance(ExcelType);
ExcelType.InvokeMember("Visible", BindingFlags.SetProperty, null,
ExcelInst, new object[1] {true});
Trying to do very much of that will sap the lifeblood from you.
COM is so much easier if you can use early bound dispatch rather than late bound as shown above. Are you sure you can't find the right reference for the COM object?
If you use .NET Framework 4.0 and above, you can use this pattern:
public sealed class Application: MarshalByRefObject {
private readonly dynamic _application;
// Methods
public Application() {
const string progId = "Broker.Application";
_application = Activator.CreateInstance(Type.GetTypeFromProgID(progId));
}
public Application(dynamic application) {
_application = application;
}
public int Import(ImportType type, string path) {
return _application.Import((short) type, path);
}
public int Import(ImportType type, string path, string defFileName) {
return _application.Import((short) type, path, defFileName);
}
public bool LoadDatabase(string path) {
return _application.LoadDatabase(path);
}
public bool LoadLayout(string path) {
return _application.LoadLayout(path);
}
public int Log(ImportLog action) {
return _application.Log((short) action);
}
public void Quit() {
_application.Quit();
}
public void RefreshAll() {
_application.RefreshAll();
}
public void SaveDatabase() {
_application.SaveDatabase();
}
public bool SaveLayout(string path) {
return _application.SaveLayout(path);
}
// Properties
public Document ActiveDocument {
get {
var document = _application.ActiveDocument;
return document != null ? new Document(document) : null;
}
}
public Window ActiveWindow {
get {
var window = _application.ActiveWindow;
return window != null ? new Window(window) : null;
}
}
public AnalysisDocs AnalysisDocs {
get {
var analysisDocs = _application.AnalysisDocs;
return analysisDocs != null ? new AnalysisDocs(analysisDocs) : null;
}
}
public Commentary Commentary {
get {
var commentary = _application.Commentary;
return commentary != null ? new Commentary(commentary) : null;
}
}
public Documents Documents {
get {
var documents = _application.Documents;
return documents != null ? new Documents(documents) : null;
}
}
public string DatabasePath {
get { return _application.DatabasePath; }
}
public bool Visible {
get { return _application.Visible != 0; }
set { _application.Visible = value ? 1 : 0; }
}
public string Version {
get { return _application.Version; }
}
}
}
Next you must wrap all AmiBroker OLE Automation classes. For example wrap Commentary class:
public sealed class Commentary : MarshalByRefObject {
// Fields
private readonly dynamic _commentary;
// Methods
internal Commentary(dynamic commentary) {
_commentary = commentary;
}
public void Apply() {
_commentary.Apply();
}
public void Close() {
_commentary.Close();
}
public bool LoadFormula(string path) {
return _commentary.LoadFormula(path);
}
public bool Save(string path) {
return _commentary.Save(path);
}
public bool SaveFormula(string path) {
return _commentary.SaveFormula(path);
}
}
Here's a snippet from the C# code I used to automate Amibroker (from when I went down that path). You'll need to reference System.Runtime.Interopservices
System.Type objType = System.Type.GetTypeFromProgID("Broker.Application");
dynamic comObject = System.Activator.CreateInstance(objType);
comObject.Import(0, fileName, "default.format");
comObject.RefreshAll();
Typing a dot won't bring up the comObject internal methods, though.
All I can say about this method is - it works, like a charm, but stay away from it, like David said. I got my inspiration for this method from:
http://www.codeproject.com/Articles/148959/How-the-new-C-dynamic-type-can-simplify-access-to
For another angle of attack, you may want to check out (I think this is early binding):
http://adamprescott.net/2012/04/05/net-vb6-interop-tutorial/
Hope at least some of this help you. I've used both these methods with Amibroker and C#, but I ended up leaving them behind. COM and Amibroker don't mix well. Even TJ says so.
Good luck anyway.
ami2py will read AmiBroker data into python. The current version is .0.8.1 WARNING: It only provides day resolution on data.
The following few lines of code will read a symbol from AmiBroker into a pandas df
import pandas
import ami2py
folder='C:/Program Files/AmiBroker/Databases/StockCharts'
symbol='indu'
df = pandas.DataFrame()
symbolData = ami2py.AmiDataBase(folder).get_dict_for_symbol(symbol)
for z in ['Year', 'Month', 'Day', 'Open', 'High', 'Low', 'Close', 'Volume'] :
df[symbol+':'+z] = symbolData[z]
print(df.describe())