How to get Angularjs scope variable after reloadWithDebugInfo? - puppeteer

I have an angularjs web page and want to get the specified element's scope. But after executing the reloadWithDebugInfo function, the result is null;
private Page _page;
private Browser _browser;
private async void button1_ClickAsync(object sender, EventArgs e)
{
try
{
await initAsync();
await test2Async();
}
catch (Exception ex)
{
MessageBox.Show("Error : " + ex.Message);
}
}
private async Task initAsync()
{
_browser = await Puppeteer.LaunchAsync(new LaunchOptions
{
Headless = false,
ExecutablePath = #"c:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
Timeout = 60000
});
}
private async Task test2Async()
{
try
{
_page = await _browser.NewPageAsync();
await _page.GoToAsync("https://SOME Angular JS WebPage");
await _page.EvaluateFunctionAsync(#"() => angular.reloadWithDebugInfo()");
var scopeContent = await _page.EvaluateFunctionAsync("() => angular.element(document.getElementsByClassName('left-column-v3')).scope() ");
// scopeContent is null. why? (the above javascript code runs successfully in the chrome dev console.)
}
catch (Exception ex)
{
MessageBox.Show("Error : " + ex.Message);
}
}
These statements works well in chrome dev tools.
I expect the json content of the scope, but that is null;
Update:
sorry, I forgot something after Scope().
I want a variable in the scope, not scope itself:
var scopeContent = await _page.EvaluateFunctionAsync("() => angular.element(document.getElementsByClassName('left-column-v3')).scope().SomeVariable ");

The problem is that the result of the scope function is not serializable.
You would need to build a serializable object inside the EvaluateFunctionAsync and return that.

Related

Where to catch exceptions when using Task.ContinueWith?

I would like to create an async method with Task that creates a file and immediately proceeds to executing next task which uploads created file to cloud.
Here is how this method looks:
public async TaskCreateAndUploadAsync()
{
await Task.Run(() =>
{
try
{
var _writeFile = new WriteFile(...);
_writeFile.DoWork();
}
catch (Exception e)
{
//Log..
}
}).ContinueWith((result) =>
{
if (!result.IsFaulted)
{
try
{
storage.UploadCreatedObject(...);
}
catch (Exception e)
{
//Log..
}
}
});
}
My question is: Is the way how I catch exceptions in each Task individually correct or I should use one try-catch block around whole "Task..Task.ContinueWith"?
Where to catch exceptions when using Task.ContinueWith?
The proper answer is "don't use ContinueWith". For asynchronous code, you can use await instead; for synchronous code like this, you can just use nothing:
public async TaskCreateAndUploadAsync()
{
await Task.Run(async () =>
{
try
{
var _writeFile = new WriteFile(...);
_writeFile.DoWork();
storage.UploadCreatedObject(...);
}
catch (Exception e)
{
//Log..
}
});
}
However, wrapping a method body in Task.Run like this is an antipattern; it's better to keep the method synchronous and have callers use Task.Run:
public void TaskCreateAndUpload()
{
try
{
var _writeFile = new WriteFile(...);
_writeFile.DoWork();
storage.UploadCreatedObject(...);
}
catch (Exception e)
{
//Log..
}
}
From your method names, it sounds like some of them should be asynchronous. I/O is inherently asynchronous. So, if you have truly asynchronous I/O (i.e., not using Task.Run for fake-asynchrony), then your resulting method may look like this:
public async Task TaskCreateAndUploadAsync()
{
try
{
var _writeFile = new WriteFile(...);
await _writeFile.DoWorkAsync();
await storage.UploadCreatedObjectAsync(...);
}
catch (Exception e)
{
//Log..
}
}
Note the use of await instead of ContiueWith in this last example.

Non Blocking UI with Gmail Api in Winrt

I am developing an gmail client in uwp and want to use gmail api but the want the get messages asynchronous wihout blocking the ui the following method blocks the ui.
public async Task<IEnumerable<Message>> GetMessagesAsync(string userId, string labelId, long maxResults)
{
await AuthenticateAsync();
List<Message> result = new List<Message>();
UsersResource.MessagesResource.ListRequest request = service.Users.Messages.List(userId);
request.LabelIds = labelId;
request.MaxResults = maxResults;
try
{
ListMessagesResponse response = request.Execute();
result.AddRange(response.Messages);
}
catch (Exception e)
{
//Console.WriteLine("An error occurred: " + e.Message);
}
return result;
}
Use Task.Run for non blocking
public async Task<IEnumerable<Message>> GetMessagesAsync(string userId, string labelId, long maxResults)
{
await AuthenticateAsync();
return await Task.Run(() =>
{
List<Message> result = new List<Message>();
UsersResource.MessagesResource.ListRequest request = service.Users.Messages.List(userId);
request.LabelIds = labelId;
request.MaxResults = maxResults;
try
{
ListMessagesResponse response = request.Execute();
result.AddRange(response.Messages);
}
catch (Exception e)
{
//Console.WriteLine("An error occurred: " + e.Message);
}
return result;
});
}

'System.IO.FileNotFoundException' after calling RfcommDeviceService.FromIdAsync(...)

I'm trying to make a function to connect to a specific Bluetooth device. I'm somewhat sure the DeviceInformation parameter is valid so the issue should be just contained to the function below. A short period of time after the line RfcommDeviceService.FromIdAsync(...) I will see A first chance exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.ni.dll in the Output in Visual Studio and then see The program '...' has exited with code -1 (0xffffffff).. Additionally, the exception is not being caught by try{} catch(Exception e){} so that might mean there is an issue elsewhere.
public async Task<bool> Connect(DeviceInformation deviceInformation)
{
try
{
await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
{
rfcommService = await RfcommDeviceService.FromIdAsync(deviceInformation.Id);
});
System.Diagnostics.Debug.WriteLine("edfdshjkfdsklfdjslkf");
if (rfcommService == null)
{
return false;
}
System.Diagnostics.Debug.WriteLine(rfcommService.Device.ToString());
await streamSocket.ConnectAsync(
rfcommService.ConnectionHostName,
rfcommService.ConnectionServiceName);
dataReader = new DataReader(streamSocket.InputStream);
dataWriter = new DataWriter(streamSocket.OutputStream);
return true;
}
catch (Exception e)
{
Debug.WriteLine("Exception while connecting: " + e.Message);
Debug.WriteLine(e.StackTrace);
return false;
}
}
I also have the following Capabilities in Package.appxmanifest:
<Capabilities>
<Capability Name="internetClientServer" />
<DeviceCapability Name="proximity" />
<m2:DeviceCapability Name="bluetooth.rfcomm">
<m2:Device Id="any">
<m2:Function Type="name:serialPort" />
</m2:Device>
</m2:DeviceCapability>
</Capabilities>
Turns out the DeviceInformation of making a Bluetooth connection is for WinRT desktop/tablet and not phone. The solution was to use a PeerInformation method.
The function now looks like the following:
public async Task<bool> Connect(PeerInformation peerInfo)
{
streamSocket = new StreamSocket();
try
{
await streamSocket.ConnectAsync(peerInfo.HostName, "{00001101-0000-1000-8000-00805f9b34fb}");
}
catch (System.Exception)
{
return false;
}
return true;
}
Writing can be done using await streamSocket.OutputStream.WriteAsync(rawMessage.AsBuffer());
. Reading I still haven't figured out how to do yet but the issue I was having with this question was resolved by the above.

How to Store Object to windows phone 8.1

In wp8.0 we can store object to IsolatedStorageSettings. wp8.1 object was not storing. Is there any way to store object to wp8.1.
WRITE OBJECT CODE
NewsList = new ObservableCollection<New>(e.News);
var FileName = "News.xml";
DataContractSerializer serializer = new DataContractSerializer(typeof(ObservableCollection<New>));
var localFolder = ApplicationData.Current.LocalFolder;
var file = await localFolder.CreateFileAsync(FileName,CreationCollisionOption.ReplaceExisting);
IRandomAccessStream sessionRandomAccess = await file.OpenAsync(FileAccessMode.ReadWrite);
IOutputStream sessionOutputStream = sessionRandomAccess.GetOutputStreamAt(0);
serializer.WriteObject(sessionOutputStream.AsStreamForWrite(), NewsList);
READ OBJECT CODE
var FileNameNews = "News.xml";
DataContractSerializer serializer = new DataContractSerializer(typeof(ObservableCollection<New>));
var localFolder = ApplicationData.Current.LocalFolder;
var newsFile = await localFolder.GetFileAsync(FileNameNews);
IInputStream sessionInputStream = await newsFile.OpenReadAsync();
newsVM = new NewsViewModel();
NewsVM.NewsList = (ObservableCollection<New>)serializer.ReadObject(sessionInputStream.AsStreamForRead());
im getting error on this link
IInputStream sessionInputStream = await newsFile.OpenReadAsync();
What mistake is there this code??
Thanks
This is how I do it. No using statements. I try to avoid the Stream syntax as much as possible.
Your error is very likely either because of concurrency (accessing the same file at the same time will throw an exception), or because the stream was not closed properly. I think it is the latter.
You do not dispose of your Stream objects properly (learn the using () {} syntax), which means that the stream remains OPEN after you're done writing. That means you hit the concurrency issue the second time you write, because you're trying to access a stream that's already open.
public async Task CreateOrUpdateData(string key, object o)
{
try
{
if (o != null)
{
var sessionFile = await _localFolder.CreateFileAsync(key, CreationCollisionOption.ReplaceExisting);
var outputString = JToken.FromObject(o).ToString();
await FileIO.WriteTextAsync(sessionFile, outputString);
}
}
catch (Exception e)
{
Debug.WriteLine("Encountered exception: {0}", e);
}
}
public async Task<T> GetDataOrDefault<T>(string key, T defaultValue)
{
try
{
T results = defaultValue;
var sessionFile = await _localFolder.CreateFileAsync(key, CreationCollisionOption.OpenIfExists);
var data = await FileIO.ReadTextAsync(sessionFile);
if (!String.IsNullOrWhiteSpace(data))
{
results = JToken.Parse(data).ToObject<T>();
}
return results;
}
catch (Exception e)
{
Debug.WriteLine("Encountered exception: {0}", e);
}
return defaultValue;
}

Windows phone httpclient not working

I have the following code. The async call never returns anything. Even for google.com.
try
{
using (
var client = new HttpClient()) {
var response = client.GetAsync("http://www.google.com");
Debug.WriteLine("Coming here1"+response.Result.IsSuccessStatusCode);
if (response.Result.IsSuccessStatusCode)
{
// by calling .Result you are performing a synchronous call
Debug.WriteLine("Coming here1");
var responseContent = response.Result.Content;
// by calling .Result you are synchronously reading the result
string responseString = responseContent.ReadAsStringAsync().Result;
//Console.WriteLine(responseString);
}
else { Debug.WriteLine("else"); }
}
}
catch(Exception e)
{
Debug.WriteLine(e.ToString());
}
}
Try This
try{
WebClient wc = new WebClient();
wc.DownloadStringCompleted+= (sender,args) => {
Debug.WriteLine(args.results);
};
wc.DownloadStringAsync(new Uri(#"http://www.Google.com",UriKind.RelativeOrAbsolute));
}
catch(Exception e){ Debug.WriteLine(e.Message); }
You don't appear to be awaiting your Async call.
Try changing var response = client.GetAsync("http://www.google.com"); to var response = await client.GetAsync("http://www.google.com");
Remember to mark your method as async.
you're also blocking on your async call ReadAsStringAsync().Result. As with client.GetAsync, make sure to await the call instead of blocking with Result. This blog post speaks a bit on the topic.
Read up a bit on async/await. You'll love it once you get the hang of it.