I am trying to make a basic 'Silverlight Class Library' in Silverlight 4 to return basic Facebook Information using Facebook's Graph API, but I am only getting empty strings being returned.
I am using the following code:
string _Response = "";
public string GetFacebookMe(string access_token)
{
WebClient facebookClient = new WebClient();
facebookClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(facebookClientDownloadStringCompleted);
facebookClient.DownloadStringAsync(new Uri("https://graph.facebook.com/me" + "?access_token=" + access_token));
string ret = _Response;
return ret;
}
private void facebookClientDownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
_Response = e.Result;
}
else
{
_Response = e.Error.Message;
}
}
I tried while debugging to init _Response to the value "Default", and the string "Default" was consequently being returned. I have been messing with this for a while and I'm not sure where I'm going wrong.
Thanks in advance!
It means a lot of effort to use directly WebClient. When using Silverlight and .Net Framework 4.0 you may use Facebook C# SDK at Codeplex
Usage of the SDK is excellently covered in this blog by Prabir Shrestha
Related
I am new to react-native and I seek your help please. What I am planning to do is to get the app icon associated with an app that the user has installed on his device.
I did take a look at this code and realized that I have no way of passing it back to my JS.
Here is what I am doing currently.
private List<String> getNonSystemApps() {
List<PackageInfo> packages = this.reactContext
.getPackageManager()
.getInstalledPackages(0);
List<String> ret = new ArrayList<>();
for (final PackageInfo p: packages) {
if ((p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("name", p.packageName);
jsonObject.put("firstInstallTime", p.firstInstallTime);
jsonObject.put("installLocation", p.installLocation);
jsonObject.put("applicationInfo", p.applicationInfo);
jsonObject.put("permissions", getPermissionsByPackageName(p.packageName));
Drawable icon = reactContext.getPackageManager().getApplicationIcon(p.packageName);
ret.add(jsonObject.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return ret;
}
Can you please help me out with this ?
Thanks
Edit
I managed to get it working, based on Aaron's suggestion, I created another private function just to work with the images. This function will generate the base 64 version of an app's icon.
private String getBitmapOfAnAppAsBase64(String packageName) {
if(packageName.isEmpty() ) return new String("");
String base64Encoded = "";
Bitmap bitmap;
try {
Drawable appIcon = this.reactContext.getPackageManager().getApplicationIcon(packageName);
if(appIcon instanceof BitmapDrawable) {
bitmap= ((BitmapDrawable)appIcon).getBitmap();
} else {
bitmap = Bitmap.createBitmap(appIcon.getIntrinsicWidth(), appIcon.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
}
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream .toByteArray();
base64Encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
} catch(Exception e) {
Log.d(TAG,"An error was encounted while getting the package information. The error follows : " + e.toString());
}
return base64Encoded;
}
I then use this generated string in my original function, with the following modifications.
Old Non working code
Drawable icon = reactContext.getPackageManager().getApplicationIcon(p.packageName);
New working code
jsonObject.put("icon", getBitmapOfAnAppAsBase64(p.packageName));
and then in React-Native - its a piece of pie, since it supports base64 already.
"icon" : 'data:image/png;base64,'+installAppObj.icon
Huge thanks to Aaron , for guiding me in the correct direction.
If you haven't already, read through the entire Android Native Modules page. It's not that long and addresses several issues you're likely to run into.
Only these types can be sent to your JS code (via a #ReactMethod):
Boolean -> Bool
Integer -> Number
Double -> Number
Float -> Number
String -> String
Callback -> function
ReadableMap -> Object
ReadableArray -> Array
So you effectively have two options:
Encode the Drawable to one of these types, then decode it on the JavaScript side, or
Write the file to disk, and send the path over
I'm not sure what type of Drawable the icon is or if there are guarantees. But any of them should be convertible in some way. For example if it's a Bitmap you can do a Bitmap to Base64 String conversion.
I am completely new to this but trying to learn. I'm sure there is a simple answer but I don't know enough to Google the right problem. I'm sure this must be a common problem.
In using Visual Studio 2010, WPF , .net 4.0, on a MVVM pattern using a WCF service, I have this which works perfectly:
private void RefreshEncountertimes()
{
// consume the WCF service.
this.dataservice.GetEncounterDetailsCompleted += (s, e) =>
{
this.Encounterdetails = e.Result;
};
// call the WCF service
this.dataservice.GetEncounterDetailsAsync(Calendardate);
}
where Encounterdetails is:
private IEnumerable<EncounterDetail> encounterdetails;
public IEnumerable<EncounterDetail> Encounterdetails
{
get
{
return this.encounterdetails;
}
set
{
this.encounterdetails = value;
this.OnPropertyChanged("Encounterdetails");
}
}
However, when trying to get the count on the returned Encounterdetails like this:
// search for encounters of the calendardate
private void RefreshEncountertimes()
{
// consume the WCF service.
this.dataservice.GetEncounterDetailsCompleted += (s, e) =>
{
this.Encounterdetails = e.Result;
this.ListCount = Encounterdetails.Count(); //<---CRASHES WITH INFINITIE LOOP
};
// call the WCF service
this.dataservice.GetEncounterDetailsAsync(Calendardate);
}
where ListCount is:
private int listcount;
public int ListCount
{
get
{
return listcount;
}
set
{
this.listcount = value;
OnPropertyChanged("ListCount");
CanFindPatient = ListCount > 0;
}
}
It crashes with:
Cannot evaluate expression because the current thread is in a stack overflow state.
So how do you get the Count of a returned IEnumerable from an asynchronous procedure?
Any help would be appreciated.
I have a problem with the MediaElement in my windows phone (8) application. It's working fine until I navigate to some other page and come back on the page containing the MediaElement.
I have the following code to play a stream coming from Bing Translator APIs:
private void TranslationService_SpeakComplete(object sender, SpeakCompleteEventArgs e)
{
var stream = e.Stream;
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
try
{
MediaElement.Stop();
MediaElement.Source = null;
string filename = "FlipNLearnItAudio";
using (var isf = IsolatedStorageFile.GetUserStoreForApplication())
{
bool fileExists = isf.FileExists(filename);
if (fileExists)
{
isf.DeleteFile(filename);
}
var isfs = isf.CreateFile(filename);
using (isfs)
{
Helpers.SaveFile(stream, isfs);
isfs.Position = 0;
MediaElement.AutoPlay = true;
MediaElement.SetSource(isfs);
}
}
}
catch (Exception ex)
{
//TODO: log exception
}
});
}
The biggest problem is that there's no exception.... the "MediaElement.SetSource(isfs);" is called normally without any exception!
Do you have any idea of what can happen?
Thanks for any help!
Bastien
Ok, I find a solution to my problem. I put the MediaElement in the App.xaml resources and now it's working fine...
But it doesn't explain why it was not working with the MediaElement in the MainPage.xaml.
If somebody has the answer, I would be very interested to hear it ;-).
Just getting my head around WCF, so forgive me for the inelegant coding.
The issue I'm having is I seem to be submitting data twice to my service (see screenshot), even though (I think) I'm only doing it once.
Could someone please let me know what I might be doing wrong? Or even just suggest a better way to do it if I'm doing it inefficiently.
Code follows:
public void EndOfLevel()
{
GlobalVariable.TotalQuestionsAsked = 10;
GlobalVariable.CorrectDecimal = GlobalVariable.Correct / GlobalVariable.TotalQuestionsAsked;
//Show loading screen
UploadingScreen.Visibility = Visibility.Visible;
//Submit this levels results.
Service1Client client = null;
client = new Service1Client();
//Gather the results and details
Result thislevel = new Result();
thislevel.Datetime = DateTime.Now;
thislevel.result = GlobalVariable.CorrectDecimal;
thislevel.TimesTable = GlobalVariable.NeedsHelpWith;
//submit them
try
{
client.SubmitResultAsync(thislevel);
}
catch
{
MessageBox.Show("Error uploading data");
}
finally
{
client.Close();
Results r3 = new Results();
this.NavigationService.Navigate(r3);
}
}
WCF Test Client:
Cheers,
Nick
If I may, here's a pattern for managing our asynchronous calls between our WPF applications and our WCF Services.
In this section we have a public accessor to our service client that ensures that the connection to the client is open prior to calling a service method:
public static MyServiceClient Client
{
get
{
return GetMyServiceClient();
}
}
private static MyServiceClient client;
private static MyService.MyServiceClient GetMyServiceClient()
{
VerifyClientConnection();
return client;
}
private static void VerifyClientConnection()
{
if (client == null || client.State == System.ServiceModel.CommunicationState.Closed)
{
client = new MyService.MyServiceClient();
}
}
And in this section is an example of our asynchronous call and callback pattern (this example shows the delegate and callback we're using for passing exception data to our service):
public delegate void LogExceptionCompletedEvent();
public static LogExceptionCompletedEvent LogExceptionCompleted;
public static void LogExceptionAsync(SilverlightException exception)
{
string json = JsonConvert.SerializeObject(exception);
Client.LogExceptionCompleted -= client_LogExceptionCompleted;
Client.LogExceptionCompleted += client_LogExceptionCompleted;
Client.LogExceptionAsync(json);
}
private static void client_LogExceptionCompleted(object sender, AsyncCompletedEventArgs e)
{
if (LogExceptionCompleted != null)
{
LogExceptionCompleted();
}
}
In this example, a view model could attach an event handler to the LogExceptionCompleted delegate and in turn receive the result of the callback when it returns from the service.
We basically repeat this pattern for the asynchronous WCF service calls we need to make from our application and it keeps them very organized as well as unit testable.
How to create a simple WPF Authentication for WPF application?
For example:
First time a user should registry then login.
Users login and password should be saved as txt file(encrypted).
If process of authentication is successful,then it should redirect to another existed window.
I'm a beginner in WPF.
I've searched about this question,but didn't find what I need.
I need a simple,step by step explanation of how to do it.
Thanks in advance! :)
I am also learning so in order to exercise a bit i have created a very simple example for you. It is probably unprofessional and unsafe but i think (hope) it is possible to extend it somehow :).
Firstly you need to create simple WPF windows (use txt/btn+Name naming convention):
For both windows add
using System.IO;
Then you need to add events for buttons and modify code for both windows:
public partial class LoginWindow : Window
{
public LoginWindow()
{
InitializeComponent();
}
// This is really bad/weak encryption method
String WeakDecryptMethod(String textIn)
{
Char[] temp = textIn.ToArray<Char>();
for (int i = 0; i < textIn.Length; i++)
{
temp[i] = (char)((int)temp[i] - 3);
}
return new String(temp);
}
private void btnRegister_Click(object sender, RoutedEventArgs e)
{
RegisterWindow newWindow = new RegisterWindow();
newWindow.ShowDialog();
}
private void btnOK_Click(object sender, RoutedEventArgs e)
{
// If file exist and login and password are "correct"
if (File.Exists("Users.txt")
&& txtLogin.Text.Length >= 4
&& txtPass.Text.Length >= 4)
{
using (StreamReader streamReader = new StreamReader("Users.txt"))
{
// While there is something in streamReader read it
while (streamReader.Peek() >= 0)
{
String decryptedLogin = WeakDecryptMethod(streamReader.ReadLine());
String decryptedPass = WeakDecryptMethod(streamReader.ReadLine());
if (decryptedLogin == txtLogin.Text && decryptedPass == txtPass.Text)
{
ProtectedWindow protectedWindow = new ProtectedWindow();
this.Close();
protectedWindow.Show();
break;
}
}
}
}
}
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
}
And code for Register window:
public partial class RegisterWindow : Window
{
public RegisterWindow()
{
InitializeComponent();
}
// This is really bad/weak method to encrypt files
String WeakEncryptMethod(String textIn)
{
Char[] temp = textIn.ToArray<Char>();
for (int i = 0; i < textIn.Length; i++)
{
temp[i] = (char)((int)temp[i] + 3);
}
return new String(temp);
}
private void btnRegister_Click(object sender, RoutedEventArgs e)
{
// If file exist and login and password are "correct"
if (File.Exists("Users.txt")
&& txtLogin.Text.Length >= 4
&& txtPass.Text.Length >= 4
&& txtPass.Text == txtPassCheck.Text)
{
StringBuilder stringBuilder = new StringBuilder();
using (StreamReader streamReader = new StreamReader("Users.txt"))
{
stringBuilder.Append(streamReader.ReadToEnd());
}
using (StreamWriter streamWriter = new StreamWriter("Users.txt"))
{
streamWriter.Write(stringBuilder.ToString());
streamWriter.WriteLine(WeakEncryptMethod(txtLogin.Text));
streamWriter.WriteLine(WeakEncryptMethod(txtPass.Text));
}
this.Close();
}
}
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
}
In order to work application need to have access to file "Users.txt" which needs to be placed in the same folder.
Notes:
It will be better if you will use some proper encryption functions and probably create separate class for it. Additionally i am almost sure that it will not work properly with login and password which contains the last 3 characters from the end of ASCII tables.
In my opinion it is a bad idea to store login and password data in *.txt file :).
As far i know C# code is very easily reverse engineered so probably it will be better to hide encryption/decryption part somehow. I do not know much about it, but u will be able to read more [here] 2 and probably uncle Google will be able to help.
Code is very simple and there is probably a lot of possibilities to extend it (more file handling stuff, TextBox validation for proper input and password strength calculations)