import {
browser,
Config
} from 'protractor';
//import {browser, element, By, by, protractor, ElementFinder, ExpectedConditions, WebElement, Key } from "#syncfusion/ej2-base/e2e/index"
var fs = require('fs')
describe("protractor screenshot", () => {
browser.manage().window().setPosition(0, 0);
it("Demo", async (done) => {
browser.get("file:///D:/New%20folder/ej2-documenteditor-e2e/demos/CR_Issues/samples/height/image.html");
browser.sleep(2000);
function writeScreenShot(data: string, filename: string) {
var stream = fs.createWriteStream(filename);
stream.write(new Buffer(data, 'base64'));
stream.end();
}
browser.executeScript('window.scrollTo(0,document.body.scrollHeight)');
screenShotUtils.takeScreenshot({
saveTo: "fullpageScreenshot.png"
})
});
});
Im getting [Cannot find name 'screenShotUtils'.]this error comes after importing in protractor .js.I have to take screenshot of the image in the website and compare with the already present image using protractor
in your code you have no module or object called screenShotUtils , you should be trying something like:
https://www.protractortest.org/#/api?view=webdriver.WebElement.prototype.takeScreenshot
function writeScreenShot(data, filename) {
var stream = fs.createWriteStream(filename);
stream.write(new Buffer(data, 'base64'));
stream.end();
}
var foo = element(by.id('foo'));
//of element
foo.takeScreenshot().then((png) => {
writeScreenShot(png, 'foo.png');
});
//of entire page in viewport
browser.takeScreenshot().then((png) => {
writeScreenShot(png, 'foo.png');
});
Related
I'm writing a web-gallery scraper and I want to parallel the processing for files as much as possible with TPL Dataflow.
To scrape, I first get the gallery main page and parse the HTML to get the image page links as a list. Then I go to each page in the list and parse the HTML to get the link to the image which I then want to save to disk.
Here's the outline of my program:
var galleryBlock = new TransformBlock<Uri, IEnumerable<Uri>>(async uri =>
{
// 1. Get the page
// 2. Parse the page to get the urls of each image page
return imagePageLinks;
});
var imageBlock = new TransformBlock<Uri, Uri>(async uri =>
{
// 1. Go to the url and fetch the image page html
// 2. Parse the html to retrieve the image url
return imageUri;
});
var downloadBlock = ActionBlock<Uri>(async uri =>
{
// Download the image from uri to list
});
var opts = new DataflowLinkOptions { PropagateCompletion = true};
galleryBlock.LinkTo(imageBlock, opts); // this doesn't work, as I'm returning a list and not a single Item. However I want to progress that block in parallel.
imageBlock.LinkTo(downloadBlock, opts);
You can use a TransformManyBlock in place of your TransformBlock:
var galleryBlock = new TransformManyBlock<Uri, Uri>(async uri =>
{
return Enumerable.Empty<Uri>(); //just to get it compiling
});
var imageBlock = new TransformBlock<Uri, Uri>(async uri =>
{
return null; //just to get it compiling
});
var opts = new DataflowLinkOptions { PropagateCompletion = true };
galleryBlock.LinkTo(imageBlock, opts); // bingo!
On a project I am working on, I'm building a feature that lets users generate a report - in my case, it will go on an envelope - on-demand from information stored in our database. The problem I'm trying to solve, is that a blank PDF is being generated.
I've tried some sanity checks. First I set a breakpoint in Visual Studio and ensured that the models being passed to the report had fixed data; the reports were blank. Next, I tried including a static label that's not tied to any data, to determine if it's a report data-binding issue - the static label is not appearing in the generated report either.
More stymying, is that I've used similar code in the past without issue. I have no idea why a blank PDF file would be generated in this case.
I've read the 'Similar Questions' provided by StackOverflow, specifically this question from one year ago, but it had no answers, and thus nothing to learn from it. I've also tried the requisite Google searches, but found nothing relevant.
The only thing I cannot provide is the actual ActiveReport itself. I've checked this for Silly Programmer Errors™ like having everything hidden, or transparent labels, or similar silly things. Unfortunately, I've made no such errors.
Report Code:
public partial class EnvelopeReport : SectionReport
{
public EnvelopeReport()
{
InitializeComponent();
}
internal void RunReport(IEnumerable<PrintedAddress> model)
{
if (model != null)
{
DataSource = model;
}
Run();
}
private void OnReportStart(object sender, EventArgs e)
{
Document.Printer.PrinterName = string.Empty;
PageSettings.PaperKind = PaperKind.Number10Envelope;
PageSettings.Margins.Top = 0.25f;
PageSettings.Margins.Left = 0.5f;
PageSettings.Margins.Right = 0.5f;
PageSettings.Margins.Bottom = 0.25f;
}
}
Web API Controller Code:
[HttpGet]
public HttpResponseMessage EnvelopeReport(int addressId, string attentionTo, bool isConfidential)
{
Address address = AddressRepository.GetAddress(addressId, true);
List<PrintedAddress> models = new List<PrintedAddress>
{
new PrintedAddress(address, attentionTo, isConfidential)
};
var report = new EnvelopeReport();
report.RunReport(models);
var pdfExporter = new ActiveReportsPdfExporter();
var reportBytes = pdfExporter.ExportPdf(report);
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new ByteArrayContent(reportBytes, 0, reportBytes.Length);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "Envelope Report.pdf"
};
return response;
}
PDF Exporter:
public class ActiveReportsPdfExporter
{
private readonly PdfExport _pdfExport;
public ActiveReportsPdfExporter()
{
_pdfExport = new PdfExport();
}
public byte[] ExportPdf(SectionReport report)
{
using (var stream = new MemoryStream())
{
_pdfExport.Export(report.Document, stream);
return stream.ToArray();
}
}
public Stream ExportPdfToStream(SectionReport report)
{
var stream = new MemoryStream();
_pdfExport.Export(report.Document, stream);
return stream;
}
}
Client Service (Angular):
(function () {
angular.module('app').factory('addressSvc', [
'$http', addressSvc
]);
function addressSvc($http) {
var service = {
printAddress: function(addressId, attentionTo, someFlag) {
var args = {
'addressId': thingId,
'attentionTo': attentionTo,
'isConfidential': isConfidential
};
return $http.get('/api/common/EnvelopeReport', { 'params': args });
}
};
return service;
}
})();
Client Controller (Angular):
(function() {
angular.module('app').controller('someCtrl', [
'$window', 'addressSvc', controller
]);
function controller($window, addressSvc) {
var vm = this;
vm.attentionTo = ''; // Bound to UI.
vm.isConfidential = ''; // Also bound to UI.
vm.address = {}; // Unimportant how we get this.
vm.printAddress = printAddress;
function printAddress() {
addressSvc.printAddress(vm.address.id, vm.attentionTo, vm.isConfidential)
.then(function(result) {
var file = new Blob([result], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
if(window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(file, 'Envelope.pdf');
} else {
$window.open(fileURL);
}
});
}
}
)();
Question: Why is this code generating an empty PDF? I've used the Report/API Controller structure successfully in the past to generate PDFs, but usually in the context of MVC, not Web API. Another potential point of failure is the client code - I've not previously passed reports between server and client this way.
So, it turns out my server-side code was completely sane. The Client code was off.
Instead of Blobbing the data returned from the server and all of that work, what I instead needed to do was build a URL...and call $window.open(url); This is because my server code as it stands will return the PDF file as-is.
I try to get an image from my database (in this case localhost) but it doesn't seem to work. I'm binding the result (URL to the image) to my XAML without any luck. I get no error but an Image does not appear either. This is my code.
Maybe it has something to do with my URL?
When I used parse (as backend) they gave us a URL that started like this:
"http://files.parsetfss.com/....."
My URL just starts with "localhost". Do I need to adjust the backend code somehow?
My cs file where I retrieve the http and jsondata:
static public async Task<JObject> getImages ()
{
var httpClientRequest = new HttpClient ();
var result = await httpClientRequest.GetAsync ("http://www.localhost.com/image.php");
var resultString = await result.Content.ReadAsStringAsync ();
var jsonResult = JObject.Parse (resultString);
return jsonResult;
}
It looks like this on the localhost:
{
"results": [
{
"GetImage": {
"ID": 1,
"Name": "Aqua",
"URL": "http://localhost.com/Images/Aquavit.jpg"
}
}]
}
This is my contentpage where I try to recieve the image:
async void clickHere (object s, EventArgs ar)
{
var createImage = await phpApi.getImages ();
list = new List<pictures> ();
foreach (var currentItem in createImage["results"]) {
var prodPic = "";
if(currentItem["GetImage"] != null)
{
prodPic = (string)currentItem ["GetImage"]["URL"];
}
list.Add (new pictures () {
image = prodPic,
});
System.Diagnostics.Debug.WriteLine (currentItem ["GetImage"]["URL"]); //here I get the exact URL.
}
}
My class:
public class pictures
{
public string image { get; set; }
}
And its XAML:
<Image Source = "{Binding image}" />
Just in addition:
If you want to load more images and/or allow to display a placeholder while loading, I recomment the FFImageLoading library. It offers nice functionality like downloading, caching, showing placeholder and error images and most important: down sampling the image to the target size. This is always a pain on android.
You can bind strings that contain urls directly to the Source. The code would like like:
<ffimageloading:CachedImage
Source="http://thecatapi.com/?id=MTQ5MzcyNA">
</ffimageloading:CachedImage>
I think you should be using a UriImageSource instead of string. Since it's a url. Try this:
your class:
public class pictures
{
public UriImageSource image { get; set; }
}
contentpage:
prodPic = (string)currentItem ["GetImage"]["URL"];
list.Add (new pictures () {
image = new UriImageSource { Uri = new Uri(prodPic) },
});
Also I believe your list needs to be an ObservableCollection instead of a List.
I am using html2canvas to capture google map image on the click of a button.
There are lot of codes for this but I am not successful in getting an image,all I get is blank image with google icons like street view and sign in image without rendering map(just a grey background) .I used proxy for c# and here is my code. Can you guys tell me what the problem is?
$('#btn_capture').click(function ()
{
html2canvas($('#map-canvas'), {
logging: true, //Enable log (use Web Console for get Errors and Warnings)
proxy: "html2canvasproxy.ashx",
// useCORS: true,
onrendered: function (canvas) {
var img = new Image();
img.onload = function () {
img.onload = null;
document.body.appendChild(img);
};
img.onerror = function () {
img.onerror = null;
if (window.console.log) {
window.console.log("Not loaded image from canvas.toDataURL");
}
else {
alert("Not loaded image from canvas.toDataURL");
}
};
img.src = canvas.toDataURL("image/png");
}
});
});
I want to choose a picture from library or take a picture with the camera and show the result to the view (ImageView)
But according to a few posts including this one, the MvxHttpImageView I use needs a Uri to show the image (wheter it comes from file systemor camera). This implies, converting the Stream into a file and getting the Uri back.
I wrote a Picture Service that does the job:
public class PictureService : IPictureService,
IMvxServiceConsumer<IMvxPictureChooserTask>,
IMvxServiceConsumer<IMvxSimpleFileStoreService>
{
private const int MaxPixelDimension = 1024;
private const int DefaultJpegQuality = 92;
public void TakeNewPhoto(Action<string> onSuccess, Action<string> onError)
{
this.GetService<IMvxPictureChooserTask>().TakePicture(
PictureService.MaxPixelDimension,
PictureService.DefaultJpegQuality,
pictureStream =>
{
var newPictureUri = this.Save(pictureStream);
if (!string.IsNullOrWhiteSpace(newPictureUri))
onSuccess(newPictureUri);
else
onError("No picture selected");
},
() => { /* cancel is ignored */ });
}
public void SelectExistingPicture(Action<string> onSuccess, Action<string> onError)
{
this.GetService<IMvxPictureChooserTask>().ChoosePictureFromLibrary(
PictureService.MaxPixelDimension,
PictureService.DefaultJpegQuality,
pictureStream =>
{
var newPictureUri = this.Save(pictureStream);
if (!string.IsNullOrWhiteSpace(newPictureUri))
onSuccess(newPictureUri);
else
onError("No photo taken");
},
() => { /* cancel is ignored */ });
}
private string Save(Stream stream)
{
string fileName = null;
try
{
fileName = Guid.NewGuid().ToString("N");
var fileService = this.GetService<IMvxSimpleFileStoreService>();
fileService.WriteFile(fileName, stream.CopyTo);
}
catch (Exception)
{
fileName = null;
}
return fileName;
}
}
But for privacy reason, I do not want to save the picture on filesystem. The workflow is:
Take or select picture
Show it on screen (with additional info)
Save my model on server sending image to the cloud: not trace on the
device
My question is: how can I handle the Streams containing picture data without saving on filesystem?
Or
How to use a temporary storage system that is not accessible to user (ignore "rooted" device case)?
Thanks for your help.
You could try creating your own custom ImageView control:
1. Use a MemoryStream to collect the received pictureStream into a byte[] property on the ViewModel, e.g. MyBytes
pictureStream => {
var memoryStream = new MemoryStream();
pictureStream.CopyTo(memoryStream);
TheRawImageBytes = memoryStream.GetBuffer()
}
where TheRawImageBytes is:
private byte[] _theRawImageBytes;
public byte[] TheRawImageBytes
{
get { return _theRawImageBytes; }
set { _theRawImageBytes = value; RaisePropertyChanged(() => TheRawImageBytes); }
}
2. Create your own MyImageView class derived from ImageView, add the (context, attr) constructor, then expose a byte[] property on the MyImageView - when that byte[] is set then use BitmapFactory.DecodeByteArray and SetBitmap to render the picture from the incoming bytes
private byte[] _rawImage;
public byte[] RawImage
{
get { return _rawImage; }
set
{
_rawImage = value;
if (_rawImage == null)
return;
var bitmap = BitmapFactory.DecodeByteArray(_rawImage, 0,_rawImage.Length);
SetImageBitmap(bitmap);
}
}
3. Use <yourapp.namespace.to.MyImageView ... /> in the axml instead of the normal <ImageView ... />
4. In the axml bind the View byte[] property to the source ViewModel byte[] property.
local:MvxBind="{'RawImage':{'Path':'TheRawImageBytes'}}"
5. That's it - although you might want to add some error handling and do some testing
This approach is adapted from the answer to MvvmCross Android Bind Image from byte[]
As mentioned in that question, an alternative approach would be to use a standard ImageView with a custom binding instead.
For more on creating custom views/widgets based on standard views/widgets - including on how to replace <yourapp.namespace.to.MyImageView ... /> with an abbreviation <MyApp.MyImageView ... />, see http://slodge.blogspot.co.uk/2012/10/creating-custom-views-is-easy-to-do.html