Parse .net SDK Get Object - c#

I have been trying to return the string of the result but it doesn't return anything. When I do Console.WriteLine it shows the link.
But the line:
s = nzk.Get<string>("link");
doesn't do anything, and I don't know why.
Here's my code:
public string getlink(String ID)
{
ParseClient.Initialize(new ParseClient.Configuration
{
ApplicationId = "xxxxxxxxxxxxxx5335c1fxxx0f19efxxxx06787e",
Server = "http://api.assintates.net/parse/"
});
string s = "";
ParseQuery<ParseObject> query = ParseObject.GetQuery("test");
query.GetAsync(ID).ContinueWith(t =>
{
ParseObject nzk = t.Result;
Console.WriteLine(nzk.Get<string>("link")); // this works
s = nzk.Get<string>("link");// this doesn't work
});
return s;
}
class Program
{
static void Main(string[] args)
{
g_get x = new g_get();
Console.WriteLine(x.getlink("iLQLJKPoJA")); // shows nothing since i initialized the s with ""
Console.ReadLine();
}
}

Here is a little example to demonstrate your problem:
static void Main(string[] args)
{
Console.WriteLine(GetString());
Console.ReadLine();
}
private static async Task TimeConsumingTask()
{
await Task.Run(() => System.Threading.Thread.Sleep(100));
}
private static string GetString()
{
string s = "I am empty";
TimeConsumingTask().ContinueWith(t =>
{
s = "GetString was called";
});
return s;
}
Your output will be the following:
I am empty
Why? The thing to deal with is the ContinueWith()-function (see msdn).
ContinueWith returns you the Task-object. You have to await this task and in your code you didn't await it.
So simple solution call wait on your Task-object.
string s = "";
ParseQuery<ParseObject> query = ParseObject.GetQuery("test");
query.GetAsync(ID).ContinueWith(t =>
{
ParseObject nzk = t.Result;
Console.WriteLine(nzk.Get<string>("link")); // this works
s = nzk.Get<string>("link");// this doesn't work
}).Wait();
return s;
Here some more information about asynchronous programming in C#.
Edit: Some more information
You will see the console output because your task will be run anyway. But it will be run after you returned your string.

Related

C# Get MAC Address from the Access Point I am connected to

here goes my first post in here.
I am writing a program in C# .NET Framework 4.6.1. I need to somehow get the BSSID (MAC-Address) from the Access Point a device is connected to, to put it in a string variable.
I have been searching for hours over the internet. But all I have found gives me a list of all access points.
A couple of solutions try to parse from the CMD command "netsh wlan show interfaces", but doesn´t seem to work properly. Besides I don´t like the parsing approach, it´s ugly and not performance friendly at all.
Would be golden if someone has a solution for this an could share it.
Best Regards
Enrique
Tryed the code below from another User from here, but it doesn´t seem to give anything back. The returns are empty and for example the function GetAccessPoint isn´t even triggered. (Is the only solution I found with parsing which seemed to be plausible), but as I said, I would like to stay away from parsing.
class AccessPoint
{
public string SSID { get; set; }
public string BSSID { get; set; }
public byte Signal { get; set; }
}
class Program
{
private static async Task Main(string[] args)
{
var apList = await GetSignalOfNetworks();
foreach (var ap in apList)
{
WriteLine($"{ap.BSSID} - {ap.Signal} - {ap.SSID}");
}
Console.ReadKey();
}
private static async Task<AccessPoint[]> GetSignalOfNetworks()
{
string result = await ExecuteProcessAsync(#"C:\Windows\System32\netsh.exe", "wlan show networks mode=bssid");
return Regex.Split(result, #"[^B]SSID \d+").Skip(1).SelectMany(network => GetAccessPointFromNetwork(network)).ToArray();
}
private static AccessPoint[] GetAccessPointFromNetwork(string network)
{
string withoutLineBreaks = Regex.Replace(network, #"[\r\n]+", " ").Trim();
string ssid = Regex.Replace(withoutLineBreaks, #"^:\s+(\S+).*$", "$1").Trim();
return Regex.Split(withoutLineBreaks, #"\s{4}BSSID \d+").Skip(1).Select(ap => GetAccessPoint(ssid, ap)).ToArray();
}
private static AccessPoint GetAccessPoint(string ssid, string ap)
{
string withoutLineBreaks = Regex.Replace(ap, #"[\r\n]+", " ").Trim();
string bssid = Regex.Replace(withoutLineBreaks, #"^:\s+([a-f0-9]{2}(:[a-f0-9]{2}){5}).*$", "$1").Trim();
byte signal = byte.Parse(Regex.Replace(withoutLineBreaks, #"^.*(Signal|Sinal)\s+:\s+(\d+)%.*$", "$2").Trim());
return new AccessPoint
{
SSID = ssid,
BSSID = bssid,
Signal = signal,
};
}
private static async Task<string> ExecuteProcessAsync(string cmd, string args = null)
{
var process = new Process()
{
StartInfo = new ProcessStartInfo
{
FileName = cmd,
Arguments = args,
RedirectStandardInput = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
StandardOutputEncoding = Encoding.UTF8,
}
};
process.Start();
string result = await process.StandardOutput.ReadToEndAsync();
process.WaitForExit();
return result;
}
private static async Task<string> GetFakeData()
{
var assembly = Assembly.GetExecutingAssembly();
var resourceName = "ConsoleApp2.FakeData.txt";
using (Stream stream = assembly.GetManifestResourceStream(resourceName))
using (StreamReader reader = new StreamReader(stream))
{
return await reader.ReadToEndAsync();
}
}
private static void WriteLine(string str)
{
Console.WriteLine(str);
}
}
}
After trial and error I found a simple solution =D
class Program
{
static void Main(string[] args)
{
var wlanClient = new WlanClient();
foreach (WlanClient.WlanInterface wlanInterface in wlanClient.Interfaces)
{
var test = wlanInterface.CurrentConnection.wlanAssociationAttributes.Dot11Bssid;
Console.WriteLine(test);
}
Console.ReadKey();
}
}

How to wait for methods to finish then do new action?

I'm setting up my architechture to use Cef.Offscreen. In order to make it easy to work with I have divided some parts. But I run into a problem that controller loading finshes and serves a view before everything has been able to load.
Here's my structure --> Controller
public ActionResult InitBrowser()
{
ICefSharpRenderer renderer = RendererSingelton.GetInstance();
//Try to render something in default appdomain
renderer.LoginToTradingView(null, null);
ViewBag.SiteTitle = BrowserActions.RunScriptInNamedBrowser("loginbrowser", #"(function() {return document.title;} )();");
ViewBag.ImagesixtyfourUrl = BrowserActions.TakeScreenshot("loginbrowser");
//this is returned to fast, we have to wait for all
return View();
}
I have this class to get do some basic actions and initialize if needed.
public class CefSharpRenderer : MarshalByRefObject, ICefSharpRenderer
{
private ChromiumWebBrowser _browser;
private TaskCompletionSource<JavascriptResponse> _taskCompletionSource;
private string _name;
public void LoginToTradingView(string url, string browserName)
{
CheckIfCefIsInitialized();
BrowserFactory.GetBrowserInstance(#"https://se.tradingview.com/", "loginbrowser");
}
public void CreateBrowserAndGoToUrl(string url, string browserName)
{
CheckIfCefIsInitialized();
BrowserFactory.GetBrowserInstance(url, "browserName");
}
public void CheckIfCefIsInitialized()
{
if (!Cef.IsInitialized)
{
var settings = new CefSettings();
var assemblyPath = Path.GetDirectoryName(new Uri(GetType().Assembly.CodeBase).LocalPath);
settings.BrowserSubprocessPath = Path.Combine(assemblyPath, "CefSharp.BrowserSubprocess.exe");
settings.ResourcesDirPath = assemblyPath;
settings.LocalesDirPath = Path.Combine(assemblyPath, "locales");
var osVersion = Environment.OSVersion;
//Disable GPU for Windows 7
if (osVersion.Version.Major == 6 && osVersion.Version.Minor == 1)
{
// Disable GPU in WPF and Offscreen examples until #1634 has been resolved
settings.CefCommandLineArgs.Add("disable-gpu", "1");
}
//Perform dependency check to make sure all relevant resources are in our output directory.
Cef.Initialize(settings, performDependencyCheck: false, cefApp: null);
}
}
}
I get my browserinstance here and connected the events to be fired.
public static class BrowserFactory
{
public static ChromiumWebBrowser GetBrowserInstance(string _url, string browsername)
{
if (!BrowserContainer.CheckIfBrowserExists(browsername))
{
ChromiumWebBrowser _browser = new ChromiumWebBrowser(_url);
_browser.LoadingStateChanged += BrowserEvents.OnLoadingStateChanged;
BrowserContainer.AddDataHolder(browsername, new DataBrowserHolder { BrowserName = browsername, ChromiumWebBrow = _browser });
return _browser;
}
return null;
}
}
Browserevent loads correct page.
public static class BrowserEvents
{
public static void OnLoadingStateChanged(object sender, LoadingStateChangedEventArgs args)
{
if (args.IsLoading == false)
{
ChromiumWebBrowser cwb = (ChromiumWebBrowser)sender;
if (cwb.Address == "https://se.tradingview.com/")
{
BrowserActions.LogInToTradingView("xxxxx", "yyyyyyy", "loginbrowser");
}
}
}
}
Last my browseractions, spare med for the thread sleeps it's just under construction and it works atm.
public static class BrowserActions
{
public static void LogInToTradingView(string twusername, string twpassword, string browserName)
{
ChromiumWebBrowser _dataholder = BrowserContainer.GetDataHolderByName(browserName).ChromiumWebBrow;
IFrame ifww = _dataholder.GetMainFrame();
// var lull = #"(function() { var serielength = TradingView.bottomWidgetBar._widgets.backtesting._reportWidgetsSet.reportWidget._data.filledOrders.length; return serielength; })();";
// JavascriptResponse _js = Task.Run(async () => { return await _browser.GetMainFrame().EvaluateScriptAsync(lull); }).Result;
ifww.ExecuteJavaScriptAsync(#"(function() { window.document.getElementsByClassName('tv-header__link tv-header__link--signin js-header__signin')[0].click();})();");
// var loginusernamescript =
var loginpasswordscript = #"(function() { window.document.getElementsByClassName('tv-control-material-input tv-signin-dialog__input tv-control-material-input__control')[1].value= " + twpassword + "; })();";
var clkloginbtn = #"(function() { document.getElementsByClassName('tv-button tv-button--no-border-radius tv-button--size_large tv-button--primary_ghost tv-button--loader')[0].click();})();";
Thread.Sleep(300);
ifww.ExecuteJavaScriptAsync(#"(function() { window.document.getElementsByClassName('tv-control-material-input tv-signin-dialog__input tv-control-material-input__control')[0].click();})();");
Thread.Sleep(50);
ifww.ExecuteJavaScriptAsync(#"(function() { window.document.getElementsByClassName('tv-control-material-input tv-signin-dialog__input tv-control-material-input__control')[0].value = '" + twusername + "';})();");
Thread.Sleep(50);
ifww.ExecuteJavaScriptAsync(#"(function() { window.document.getElementsByClassName('tv-control-material-input tv-signin-dialog__input tv-control-material-input__control')[1].click();})();");
Thread.Sleep(50);
ifww.ExecuteJavaScriptAsync(#"(function() { window.document.getElementsByClassName('tv-control-material-input tv-signin-dialog__input tv-control-material-input__control')[1].value = '" + twpassword + "';})();");
Thread.Sleep(50);
ifww.ExecuteJavaScriptAsync(#"(function() { document.getElementsByClassName('tv-button tv-button--no-border-radius tv-button--size_large tv-button--primary_ghost tv-button--loader')[0].click();})();");
}
public static string TakeScreenshot(string browserName)
{
try
{
Bitmap img = Task.Run(async () => { return await BrowserContainer.GetDataHolderByName(browserName).ChromiumWebBrow.ScreenshotAsync(); }).Result;
// object mgss = img.Clone();
string baseen = ExtraFunctions.ToBase64String(img, ImageFormat.Png);
return baseen;
}
catch (Exception e)
{
var x = e.InnerException;
return null;
}
}
public static string RunScriptInNamedBrowser(string browserName, string script)
{
try
{
string str = Task.Run(async () => { return await BrowserContainer.GetDataHolderByName(browserName).ChromiumWebBrow.GetMainFrame().EvaluateScriptAsync(script); }).Result.ToString();
// object mgss = img.Clone();
return str;
}
catch (Exception e)
{
var x = e.InnerException;
return null;
}
}
}
How can I get my browser actions to report back to my controller so that I can wait for them to finish?
For a Task asynchronous operation to report back, it's possible to use Progress<T>. How that's done is detailed in Enabling Progress and Cancellation in Async APIs. The key is:
var progressIndicator = new Progress<int>(ReportProgress);
This creates a Progress<T> object that can indicate how far a task is complete, and also call a custom method (ReportProgress) at set intervals. You can create a custom class if necessary instead of using int.
So your browser actions can report back to the controller with the progress reporting method until everything is complete.

Async Functions making code not working

First, apologize me for the title... I haven't found any suiting my single case :P
I need to download an INI file to fill a Dictionary first of all. For this, I have this class:
public class Properties : INotifyPropertyChanged
{
private Dictionary<string, string> _properties;
public Properties()
{
_properties = new Dictionary<string, string>();
}
public async void Load(string uri)
{
Stream input = await connection(uri);
StreamReader rStream = new StreamReader(input);
string line;
while((line = rStream.ReadLine()) != null)
{
if(line != "")
{
int pos = line.IndexOf('=');
string key = line.Substring(0, pos);
string value = line.Substring(pos + 1);
_properties.Add(key, value);
Debug.WriteLine("Key: " + key + ", Value: " + value);
}
}
Debug.WriteLine("Properties dictionary filled with " + _properties.Count + " items.");
}
public async Task<Stream> connection(string uri)
{
var httpClient = new HttpClient();
Stream result = Stream.Null;
try
{
result = await httpClient.GetStreamAsync(uri);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
Debug.WriteLine(ex.HResult);
}
return result;
}
public string getValue(string key)
{
string result = "";
try
{
result = _properties[key];
}
catch(Exception ex)
{
Debug.WriteLine(ex.Message);
Debug.WriteLine(ex.HResult);
result = "Not found";
}
return result;
}
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged([CallerMemberName]string propertyName = "")
{
var Handler = PropertyChanged;
if (Handler != null)
Handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Mainly, the Dictionary contains a Key and a URL to download XML files to each page of the application.
The MainPage, which is the one that is gonna be fill has this code:
public MainPage()
{
this.InitializeComponent();
//Properties dictionary filling
prop = new Properties();
prop.Load("URL");
tab = new Bars.TopAppBar();
bab = new Bars.BottomAppBar();
tABar = this.topAppBar;
actvt = this.Activity;
bABar = this.bottomAppBar;
//Constructor of the UserControl
act = new Home(this, prop);
}
The constructor of the UserControl uses the MainPage as a Callback and the class Properties to look for the URL to download the XML file.
What happens is that, as Properties.Load() is an asynchronous method, is called, then the remaining lines are executed and when the program finishes, then goes back to Load() and fills the Dictionary.
As the Home constructor depends on a Value of Properties I get an Exception.
I have tried to create async voids assigning different priorities to force the program to run first one thing and then the remaining, but it hasn't worked either.
So, summarizing, I need to make sure that Properties is filled in the first place, anyone knows how to do it?
Thanks in advance!
Eva if you want to wait until the Load method is finished you have to change this method to return a Task.
public async Task LoadAsync(string uri)...
Better if you put your code in LoadedEventHandler of your page and make this method async. After that you will be able to await Properties.Load method.
If you want to call this method in constructor you can do it like this:
Task.Run(async () =>{
var task = p.LoadAsync().ConfigureAwait(false);
await task;
}).Wait()
But you have to be aware that deadlock can appear if in LoadAsync method will be await without disabled context switching (ConfigureAwait).

How to retrieve data from ebay getFeedback API

I am trying to get some data for a specified user using ebay's getFeedback API and ended up with this code.
namespace one
{
class Program
{
private static ApiContext apiContext = null;
static void Main(string[] args)
{
ApiContext apiContext = GetApiContext();
GeteBayOfficialTimeCall apiCall = new GeteBayOfficialTimeCall(apiContext);
GetFeedbackCall call = new GetFeedbackCall(apiContext);
call.UserID = "abc";
Console.WriteLine(call.GetFeedback().ToString());
Console.ReadKey();
}
static ApiContext GetApiContext()
{
if (apiContext != null)
{
return apiContext;
}
else
{
apiContext = new ApiContext();
apiContext.SoapApiServerUrl = ConfigurationManager.AppSettings["Environment.ApiServerUrl"];
ApiCredential apiCredential = new ApiCredential();
apiCredential.eBayToken = ConfigurationManager.AppSettings["UserAccount.ApiToken"];
apiContext.ApiCredential = apiCredential;
apiContext.Site = SiteCodeType.US;
return apiContext;
}
}
}
}
It prints the following line in console
eBay.Service.Core.Soap.FeedbackDetailTypeCollection
How can I get the original data?
call.GetFeedback() returning collection of FeedbackDetailType members, so you can use foreach to retrieve informations (such as feedback score and other stuff) about all particular feedback.
see complete members list of FeedbackDetailType members
here!
e.g
foreach (FeedbackDetailType feedback in call.GetFeedback())
{
Console.WriteLine(feedback.CommentText);
//and other stuff
}
Or you can use something like that
call.GetFeedback();
Console.WriteLine(call.FeedbackScore);

Getting a parameterless method to act like a Func<ReturnT>

I'm trying to make a part of my code more fluent.
I have a string extension that makes an HTTP request out of the string and returns the response as a string. So I can do something like...
string _html = "http://www.stackoverflow.com".Request();
I'm trying to write an extension that will keep trying the request until it succeeds. My signature looks something like...
public static T KeepTrying<T>(this Func<T> KeepTryingThis) {
// Code to ignore exceptions and keep trying goes here
// Returns the result of KeepTryingThis if it succeeds
}
I intend to call it something like...
string _html = "http://www.stackoverflow.com".Request.KeepTrying();
Alas, that doesn't seem to work =). I tried making it into a lambda first but that doesn't seem to work either.
string _html = (() => "http://www.stackoverflow.com".Request()).KeepTrying();
Is there a way to do what I'm trying to do while keeping the syntax fairly fluent?
Suggestions much appreciated.
Thanks.
You can't use a method group for extension methods, or lambda expressions. I blogged about this a while ago.
I suspect you could cast to Func<string>:
string _html = ((Func<string>)"http://www.stackoverflow.com".Request)
.KeepTrying();
but that's pretty nasty.
One alternative would be to change Request() to return a Func, and use:
string _html = "http://www.stackoverflow.com".Request().KeepTrying();
Or if you wanted to keep the Request method itself simple, just add a RequestFunc method:
public static Func<string> RequestFunc(this string url)
{
return () => url.Request();
}
and then call:
string _html = "http://www.stackoverflow.com".RequestFunc().KeepTrying();
Why not turn this on its head?
static T KeepTrying<T>(Func<T> func) {
T val = default(T);
while (true) {
try {
val = func();
break;
} catch { }
}
return val;
}
var html = KeepTrying(() => "http://www.stackoverflow.com".Request());
What about enhancing the Request?
string _html = "http://www.stackoverflow.com".Request(RequestOptions.KeepTrying);
string _html = "http://www.stackoverflow.com".Request(RequestOptions.Once);
RequestOptions is a enum. You could also have more options, timeout arguments, number of retries etc.
OR
public static string RepeatingRequest(this string url) {
string response = null;
while ( response != null /* how ever */ ) {
response = url.Request();
}
return response;
}
string _html = "http://www.stackoverflow.com".RepeatingRequest();
AFAIK you can write an extension method that extends a Func<T> delegate, but the compiler doesn't know what do you mean:
string _html = "http://www.stackoverflow.com".Request.KeepTrying(); // won't work
But if you explicitly cast the delegate will work:
string _html = ((Func<string>)"http://www.stackoverflow.com".Request).KeepTrying(); // works
The question here it whether the code readability is really improved in this case by an extension method.
I wouldn't write an extension method for string. Use a more specific type, like the Uri.
The full code:
public static class Extensions
{
public static UriRequest Request(this Uri uri)
{
return new UriRequest(uri);
}
public static UriRequest KeepTrying(this UriRequest uriRequest)
{
uriRequest.KeepTrying = true;
return uriRequest;
}
}
public class UriRequest
{
public Uri Uri { get; set; }
public bool KeepTrying { get; set; }
public UriRequest(Uri uri)
{
this.Uri = uri;
}
public string ToHtml()
{
var client = new System.Net.WebClient();
do
{
try
{
using (var reader = new StreamReader(client.OpenRead(this.Uri)))
{
return reader.ReadToEnd();
}
}
catch (WebException ex)
{
// log ex
}
}
while (KeepTrying);
return null;
}
public static implicit operator string(UriRequest uriRequest)
{
return uriRequest.ToHtml();
}
}
Calling it:
string html = new Uri("http://www.stackoverflow.com").Request().KeepTrying();

Categories