question link : https://leetcode.com/problems/cousins-in-binary-tree
my code :
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isCousins(TreeNode* root, int x, int y) {
//breath first search will be better in this approach
queue< pair< TreeNode * , TreeNode *> > a;
queue< pair< TreeNode * , TreeNode *> > b; // first children..then parent
a.push({root,NULL});//root-> parent = NULL
bool check = false;
auto it = a.front();
auto it2 = a.front();
while(a.size() !=0 || b.size() !=0){
if(a.size() == 0 && b.size() != 0)
a.swap(b);
//if(b.size() == 0)
// b.push({NULL,NULL});
it = a.front();
if(it.first->left != NULL)
b.push({it.first->left,it.first});
if(it.first->right != NULL)
b.push({it.first->right,it.first});
if( it.first != NULL && (it.first->val == x || it.first->val == y)){
//we need to find both in this level
//if not found return false;
while(a.size() != 0){
a.pop();
it2 = a.front();
//this is the line 40
//here....
if(it2.first != NULL && (((it2.first)->val == x) || ((it2.first)->val == y))){//all nodes are unique in value
if(it2.second == it.second)
return false;//same parent ..so not cousin
return true;//cousim
}
}
//only one of them is found at present depth
return false;
}
if(a.size() !=0)
a.pop();
}
//both not found
return false;
}
};
runtime error : Line 40: Char 60: runtime error: member access within misaligned address 0xbebebebebebebebe for type 'TreeNode', which requires 8 byte alignment (solution.cpp)
0xbebebebebebebebe: note: pointer points here
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:49:60
Since a long time, I'm trying to make work a polyline for crossplateform using.
I did it and it works well, I followed the Map Control tutorial in first, and then Highlight a Route on a Map tutorial.
I then update the code to make it reloads if a any changes comes, however, I'm getting an issue and I couldn't figure it out... It does works for Android & iOS.
polyline.Path = new Geopath(coordinates); throws Catastrophic failure (Exception from HRESULT: 0x8000FFFF (E_UNEXPECTED))
The problem is that my two others renderer (Android & iOS) works.. Maybe something isn't possible because I work with WinPhone8.1 unlike the tutorial, which is UWP.
public class CustomMapRenderer : MapRenderer
{
MapControl nativeMap;
CustomMap formsMap;
protected override void OnElementChanged(ElementChangedEventArgs<Map> e)
{
base.OnElementChanged(e);
if (e.OldElement != null)
{
nativeMap = Control as MapControl;
}
if (e.NewElement != null)
{
formsMap = (CustomMap)e.NewElement;
nativeMap = Control as MapControl;
UpdatePolyLine();
}
}
protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (this.Element == null || this.Control == null)
return;
if (e.PropertyName == CustomMap.RouteCoordinatesProperty.PropertyName)
{
UpdatePolyLine();
}
}
private void UpdatePolyLine()
{
if (nativeMap != null)
{
var coordinates = new List<BasicGeoposition>();
foreach (var position in formsMap.RouteCoordinates)
{
coordinates.Add(new BasicGeoposition() { Latitude = position.Latitude, Longitude = position.Longitude });
}
var polyline = new MapPolyline();
polyline.StrokeColor = Color.FromArgb(128, 255, 0, 0);
polyline.StrokeThickness = 5;
polyline.Path = new Geopath(coordinates);
nativeMap.MapElements.Add(polyline);
}
}
}
I also read that a key is needed, so maybe I doesn't use this key in a good way.. I tried with UWP Public Key and WinPhone8.X and earlier Key, but without success too..
Does someone has an idea? This part a really big problem in my app..
Thank in advance !
After a long time, I found why it didn't works...
If you're doing like me, if you do a HttpRequest to something as Google Direction API, then the result will comes after the first passage in the OnElementChanged().
Because formsMap.RouteCoordinates isn't null but empty, the Catastrophic failure (Exception from HRESULT: 0x8000FFFF (E_UNEXPECTED)) is thrown..
This is the good CustomMapRenderer for PolyLine use
using PROJECT;
using PROJECT.UWP;
using System.Collections.Generic;
using Windows.Devices.Geolocation;
using Windows.UI.Xaml.Controls.Maps;
using Xamarin.Forms.Maps;
using Xamarin.Forms.Maps.UWP;
using Xamarin.Forms.Platform.UWP;
[assembly: ExportRenderer(typeof(CustomMap), typeof(CustomMapRenderer))]
namespace PROJECT.UWP
{
public class CustomMapRenderer : MapRenderer
{
MapControl nativeMap;
CustomMap formsMap;
protected override void OnElementChanged(ElementChangedEventArgs<Map> e)
{
base.OnElementChanged(e);
if (e.OldElement != null)
{
nativeMap = Control as MapControl;
}
if (e.NewElement != null)
{
formsMap = (CustomMap)e.NewElement;
nativeMap = Control as MapControl;
UpdatePolyLine();
}
}
protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (this.Element == null || this.Control == null)
return;
if (e.PropertyName == CustomMap.RouteCoordinatesProperty.PropertyName)
{
UpdatePolyLine();
}
}
private void UpdatePolyLine()
{
if (formsMap != null && formsMap.RouteCoordinates.Count > 0)
{
List<BasicGeoposition> coordinates = new List<BasicGeoposition>();
foreach (var position in formsMap.RouteCoordinates)
{
coordinates.Add(new BasicGeoposition() { Latitude = position.Latitude, Longitude = position.Longitude });
}
Geopath path = new Geopath(coordinates);
MapPolyline polyline = new MapPolyline();
polyline.StrokeColor = Windows.UI.Color.FromArgb(128, 255, 0, 0);
polyline.StrokeThickness = 5;
polyline.Path = path;
nativeMap.MapElements.Add(polyline);
}
}
}
}
I want to update my UI based on the scenario when an Ad is being shown or an error occurred. I am using AdRotator v2.1. Looking at the source code it seems that the control would collapse if it could not serve an ad from various provider, and the IsAdRotatorEnabled would be set to false. But that property does not trigger an notification change. How can i detect if no ads are being shown?
Enabled="{Binding AreAdsEnabled,Mode=TwoWay,FallbackValue=true,UpdateSourceTrigger=PropertyChanged}"
This is hack i am currently using. Its quite brittle. Its looking at log message for strings to detect if an error has occurred.
public class BaseAdControl
{
public AdRotatorControl CurrentAdRotatorControl { get; set; }
private UserControl userControlWrapper;
public BaseAdControl(AdRotatorControl MyAdRotatorControl, UserControl userControlWrapper)
{
// TODO: Complete member initialization
this.CurrentAdRotatorControl = MyAdRotatorControl;
this.userControlWrapper = userControlWrapper;
MyAdRotatorControl.PlatformAdProviderComponents.Add(AdRotator.Model.AdType.PubCenter, typeof(Microsoft.Advertising.WinRT.UI.AdControl));
MyAdRotatorControl.PlatformAdProviderComponents.Add(AdRotator.Model.AdType.AdDuplex, typeof(AdDuplex.Universal.Controls.Win.XAML.AdControl));
MyAdRotatorControl.Loaded += MyAdRotatorControl_Loaded;
MyAdRotatorControl.Unloaded += MyAdRotatorControl_Unloaded;
}
#region Public Properties
#endregion Public Properties
#region Public Methods
public virtual void adDuplex_AdLoadingError(object sender, AdDuplex.Universal.Win.WinRT.Models.AdLoadingErrorEventArgs e)
{
AdDuplex.Universal.Controls.Win.XAML.AdControl adCtrl = sender as AdDuplex.Universal.Controls.Win.XAML.AdControl;
adCtrl.AdLoadingError -= adDuplex_AdLoadingError;
Utilities.logger.LogDebug(e.Error.Message);
this.userControlWrapper.Visibility = Visibility.Collapsed;
Utilities.logger.LogDebug("Updated Visibility to: " + this.userControlWrapper.Visibility);
}
public virtual async void Logger(string message)
{
Utilities.logger.LogDebug("AdRotator: " + message);
if (string.Equals(message, "No Ads available", StringComparison.CurrentCultureIgnoreCase))
{
this.userControlWrapper.Visibility = Visibility.Collapsed;
Utilities.logger.LogDebug("Updated Visibility to: " + this.userControlWrapper.Visibility);
}
else if (message.Contains("Ad created for provider"))
{
var cont = CurrentAdRotatorControl as Control;
Object adType = null;
if (cont != null)
{
await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
() =>
{
Border border = VisualTreeHelper.GetChild(CurrentAdRotatorControl, 0) as Border;
if (border != null)
{
adType = border.Child;
}
});
if (adType != null)
{
if (adType is Microsoft.Advertising.WinRT.UI.AdControl)
{
var pubsub = adType as Microsoft.Advertising.WinRT.UI.AdControl;
if (pubsub != null)
pubsub.ErrorOccurred += pubsub_ErrorOccurred;
}
else if (adType is AdDuplex.Universal.Controls.Win.XAML.AdControl)
{
var adDuplex = adType as AdDuplex.Universal.Controls.Win.XAML.AdControl;
if (adDuplex != null)
adDuplex.AdLoadingError += adDuplex_AdLoadingError;
}
else if (adType is SomaAd)
{
var smato = adType as SomaAd;
if (smato != null)
smato.GetAdError += smato_GetAdError;
}
}
}
this.userControlWrapper.Visibility = Utilities.AreAdsEnabled ? Visibility.Visible : Visibility.Collapsed;
Utilities.logger.LogDebug("Updated Visibility to: "+this.userControlWrapper.Visibility);
}
}
public virtual void MyAdRotatorControl_Loaded(object sender, RoutedEventArgs e)
{
AdRotatorControl.Log += Logger;
}
public virtual void MyAdRotatorControl_Unloaded(object sender, RoutedEventArgs e)
{
AdRotatorControl.Log -= Logger;
}
public virtual void pubsub_ErrorOccurred(object sender, Microsoft.Advertising.WinRT.UI.AdErrorEventArgs e)
{
Microsoft.Advertising.WinRT.UI.AdControl adCtrl = sender as Microsoft.Advertising.WinRT.UI.AdControl;
adCtrl.ErrorOccurred -= pubsub_ErrorOccurred;
Utilities.logger.LogDebug(e.Error + " ," + e.ErrorCode);
this.userControlWrapper.Visibility = Visibility.Collapsed;
Utilities.logger.LogDebug("Updated Visibility to: " + this.userControlWrapper.Visibility);
}
public virtual void smato_GetAdError(object sender, string ErrorCode, string ErrorDescription)
{
SomaAd adCtrl = sender as SomaAd;
adCtrl.GetAdError -= smato_GetAdError;
Utilities.logger.LogDebug(ErrorDescription + " ," + ErrorCode);
this.userControlWrapper.Visibility = Visibility.Collapsed;
Utilities.logger.LogDebug("Updated Visibility to: " + this.userControlWrapper.Visibility);
}
#endregion Public Methods
}
So hi to #ll this is my fist post/question on stackoverflow :D
I need help # following :
So i integrated the Facebook SDk sucessfully in my game but i´dont get the profile picture working ...
So i tryied it oldshool on Facebooks "Tutotial" Way and followed all steps to implement login functions and so on ...
I´ve downloaded the "friendsmash_start" Sample and implemented that Stuff ...
My Main Problem is i don´t get ahead with this problem and can´t figure out what i´m doing wrong so i´m hoping for help.
Here´s the complete Code from the MainMenu Script from the sample which is the only i´ve changed ... like in the tutorial ...
Unity shows me this Error -> "The name 'LoadPicture' does not exist in the current context ... so the errors are on these two parts of code :
"LoadPicture(Util.GetPictureURL("me", 128, 128), MyPictureCallback);" in the "OnLoggedIn" function
"LoadPicture(Util.GetPictureURL("me", 128, 128), MyPictureCallback);" in the "MyPictureCallback" function
I don´t understand it cause i searched myself in the script for this function "LoadPicture" and find nothing that was ... according to the "Tutorial" of facebook here :
https://developers.facebook.com/docs/games/unity/unity-tutorial?locale=de_DE
the function should be there cause they wrote there :
"Take a look at the LoadPicture method also in MainMenu.cs to see how we use the Unity WWW class to load the image returned by the graph API."
But i can´t find it :(
HOPE SOMEONE CAN HELP ME I DON´T GET IT ...
Have that problem unfortunately very long time ... thats enoying. :(
HERE`S THE FULL CODE OF MAINMENU.CS :
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Facebook.MiniJSON;
using System;
public class MainMenu : MonoBehaviour
{
// Inspector tunable members //
public Texture ButtonTexture;
public Texture PlayTexture; // Texture for main menu button icons
public Texture BragTexture;
public Texture ChallengeTexture;
public Texture StoreTexture;
public Texture FullScreenTexture;
public Texture FullScreenActiveTexture;
public Texture ResourcesTexture;
public Vector2 CanvasSize; // size of window on canvas
public Rect LoginButtonRect; // Position of login button
public Vector2 ResourcePos; // position of resource indicators (not used yet)
public Vector2 ButtonStartPos; // position of first button in main menu
public float ButtonScale; // size of main menu buttons
public float ButtonYGap; // gap between buttons in main menu
public float ChallengeDisplayTime; // Number of seconds the request sent message is displayed for
public Vector2 ButtonLogoOffset; // Offset determining positioning of logo on buttons
public float TournamentStep; // Spacing between tournament entries
public float MouseScrollStep = 40; // Amount score table moves with each step of the mouse wheel
public PaymentDialog paymentDialog;
public GUISkin MenuSkin;
public int CoinBalance;
public int NumLives;
public int NumBombs;
public Texture[] CelebTextures;
public string [] CelebNames;
// Private members //
private static MainMenu instance;
private static List<object> friends = null;
private static Dictionary<string, string> profile = null;
private static List<object> scores = null;
private static Dictionary<string, Texture> friendImages = new Dictionary<string, Texture>();
private Vector2 scrollPosition = Vector2.zero;
private bool haveUserPicture = false;
private float tournamentLength = 0;
private int tournamentWidth = 512;
private int mainMenuLevel = 0; // Level index of main menu
private string popupMessage;
private float popupTime;
private float popupDuration;
void Awake()
{
Util.Log("Awake");
paymentDialog = ((PaymentDialog)(GetComponent("PaymentDialog")));
// allow only one instance of the Main Menu
if (instance != null && instance != this)
{
Destroy(gameObject);
return;
}
#if UNITY_WEBPLAYER
// Execute javascript in iframe to keep the player centred
string javaScript = #"
window.onresize = function() {
var unity = UnityObject2.instances[0].getUnity();
var unityDiv = document.getElementById(""unityPlayerEmbed"");
var width = window.innerWidth;
var height = window.innerHeight;
var appWidth = " + CanvasSize.x + #";
var appHeight = " + CanvasSize.y + #";
unity.style.width = appWidth + ""px"";
unity.style.height = appHeight + ""px"";
unityDiv.style.marginLeft = (width - appWidth)/2 + ""px"";
unityDiv.style.marginTop = (height - appHeight)/2 + ""px"";
unityDiv.style.marginRight = (width - appWidth)/2 + ""px"";
unityDiv.style.marginBottom = (height - appHeight)/2 + ""px"";
}
window.onresize(); // force it to resize now";
Application.ExternalCall(javaScript);
#endif
DontDestroyOnLoad(gameObject);
instance = this;
// Initialize FB SDK
FB.Init(SetInit, OnHideUnity);
}
private void SetInit()
{
Util.Log("SetInit");
enabled = true; // "enabled" is a property inherited from MonoBehaviour
if (FB.IsLoggedIn)
{
Util.Log("Already logged in");
OnLoggedIn();
}
}
private void OnHideUnity(bool isGameShown)
{
Util.Log("OnHideUnity");
if (!isGameShown)
{
// pause the game - we will need to hide
Time.timeScale = 0;
}
else
{
// start the game back up - we're getting focus again
Time.timeScale = 1;
}
}
private void QueryScores()
{
FB.API("/app/scores?fields=score,user.limit(20)", Facebook.HttpMethod.GET, ScoresCallback);
}
private int getScoreFromEntry(object obj)
{
Dictionary<string,object> entry = (Dictionary<string,object>) obj;
return Convert.ToInt32(entry["score"]);
}
void ScoresCallback(FBResult result)
{
Util.Log("ScoresCallback");
if (result.Error != null)
{
Util.LogError(result.Error);
return;
}
scores = new List<object>();
List<object> scoresList = Util.DeserializeScores(result.Text);
foreach(object score in scoresList)
{
var entry = (Dictionary<string,object>) score;
var user = (Dictionary<string,object>) entry["user"];
string userId = (string)user["id"];
if (string.Equals(userId,FB.UserId))
{
// This entry is the current player
int playerHighScore = getScoreFromEntry(entry);
Util.Log("Local players score on server is " + playerHighScore);
if (playerHighScore < GameStateManager.Score)
{
Util.Log("Locally overriding with just acquired score: " + GameStateManager.Score);
playerHighScore = GameStateManager.Score;
}
entry["score"] = playerHighScore.ToString();
GameStateManager.HighScore = playerHighScore;
}
scores.Add(entry);
if (!friendImages.ContainsKey(userId))
{
// We don't have this players image yet, request it now
LoadPictureAPI(Util.GetPictureURL(userId, 128, 128),pictureTexture =>
{
if (pictureTexture != null)
{
friendImages.Add(userId, pictureTexture);
}
});
}
}
// Now sort the entries based on score
scores.Sort(delegate(object firstObj,
object secondObj)
{
return -getScoreFromEntry(firstObj).CompareTo(getScoreFromEntry(secondObj));
}
);
}
void OnApplicationFocus( bool hasFocus )
{
Util.Log ("hasFocus " + (hasFocus ? "Y" : "N"));
}
// Convenience function to check if mouse/touch is the tournament area
private bool IsInTournamentArea (Vector2 p)
{
return p.x > Screen.width-tournamentWidth;
}
// Scroll the tournament view by some delta
private void ScrollTournament(float delta)
{
scrollPosition.y += delta;
if (scrollPosition.y > tournamentLength - Screen.height)
scrollPosition.y = tournamentLength - Screen.height;
if (scrollPosition.y < 0)
scrollPosition.y = 0;
}
// variables for keeping track of scrolling
private Vector2 mouseLastPos;
private bool mouseDragging = false;
void Update()
{
if(Input.touches.Length > 0)
{
Touch touch = Input.touches[0];
if (IsInTournamentArea (touch.position) && touch.phase == TouchPhase.Moved)
{
// dragging
ScrollTournament (touch.deltaPosition.y*3);
}
}
if (Input.GetAxis("Mouse ScrollWheel") < 0)
{
ScrollTournament (MouseScrollStep);
}
else if (Input.GetAxis("Mouse ScrollWheel") > 0)
{
ScrollTournament (-MouseScrollStep);
}
if (Input.GetMouseButton(0) && IsInTournamentArea(Input.mousePosition))
{
if (mouseDragging)
{
ScrollTournament (Input.mousePosition.y - mouseLastPos.y);
}
mouseLastPos = Input.mousePosition;
mouseDragging = true;
}
else
mouseDragging = false;
}
// Button drawing logic //
private Vector2 buttonPos; // Keeps track of where we've got to on the screen as we draw buttons
private void BeginButtons()
{
// start drawing buttons at the chosen start position
buttonPos = ButtonStartPos;
}
private bool DrawButton(string text, Texture texture)
{
// draw a single button and update our position
bool result = GUI.Button(new Rect (buttonPos.x,buttonPos.y, ButtonTexture.width * ButtonScale, ButtonTexture.height * ButtonScale),text,MenuSkin.GetStyle("menu_button"));
Util.DrawActualSizeTexture(ButtonLogoOffset*ButtonScale+buttonPos,texture,ButtonScale);
buttonPos.y += ButtonTexture.height*ButtonScale + ButtonYGap;
if (paymentDialog.DialogEnabled)
result = false;
return result;
}
void OnGUI()
{
GUI.skin = MenuSkin;
if (Application.loadedLevel != mainMenuLevel) return; // don't display anything except when in main menu
GUILayout.Box("", MenuSkin.GetStyle("panel_welcome"));
if (!FB.IsLoggedIn)
{
GUI.Label((new Rect(179, 11, 287, 160)), "Login to Facebook", MenuSkin.GetStyle("text_only"));
if (GUI.Button(LoginButtonRect, "", MenuSkin.GetStyle("button_login")))
{
FB.Login("email,publish_actions", LoginCallback);
}
}
if (FB.IsLoggedIn)
{
string panelText = "Welcome ";
panelText += (!string.IsNullOrEmpty(GameStateManager.Username)) ? string.Format("{0}!", GameStateManager.Username) : "Smasher!";
if (GameStateManager.UserTexture != null)
GUI.DrawTexture( (new Rect(8,10, 150, 150)), GameStateManager.UserTexture);
GUI.Label( (new Rect(179 , 11, 287, 160)), panelText, MenuSkin.GetStyle("text_only"));
}
string subTitle = "Let's smash some friends!";
if (GameStateManager.Score > 0)
{
subTitle = "Score: " + GameStateManager.Score.ToString();
}
if (!string.IsNullOrEmpty(subTitle))
{
GUI.Label( (new Rect(132, 28, 400, 160)), subTitle, MenuSkin.GetStyle("sub_title"));
}
BeginButtons();
if (DrawButton("Play",PlayTexture))
{
onPlayClicked();
}
if (FB.IsLoggedIn)
{
// Draw resources bar
Util.DrawActualSizeTexture(ResourcePos,ResourcesTexture);
Util.DrawSimpleText(ResourcePos + new Vector2(47,5) ,MenuSkin.GetStyle("resources_text"),string.Format("{0}",CoinBalance));
Util.DrawSimpleText(ResourcePos + new Vector2(137,5) ,MenuSkin.GetStyle("resources_text"),string.Format("{0}",NumBombs));
Util.DrawSimpleText(ResourcePos + new Vector2(227,5) ,MenuSkin.GetStyle("resources_text"),string.Format("{0}",NumLives));
}
#if UNITY_WEBPLAYER
if (Screen.fullScreen)
{
if (DrawButton("Full Screen",FullScreenActiveTexture))
SetFullscreenMode(false);
}
else
{
if (DrawButton("Full Screen",FullScreenTexture))
SetFullscreenMode(true);
}
#endif
DrawPopupMessage();
}
public void AddPopupMessage(string message, float duration)
{
popupMessage = message;
popupTime = Time.realtimeSinceStartup;
popupDuration = duration;
}
public void DrawPopupMessage()
{
if (popupTime != 0 && popupTime + popupDuration > Time.realtimeSinceStartup)
{
// Show message that we sent a request
Rect PopupRect = new Rect();
PopupRect.width = 800;
PopupRect.height = 100;
PopupRect.x = Screen.width / 2 - PopupRect.width / 2;
PopupRect.y = Screen.height / 2 - PopupRect.height / 2;
GUI.Box(PopupRect,"",MenuSkin.GetStyle("box"));
GUI.Label(PopupRect, popupMessage, MenuSkin.GetStyle("centred_text"));
}
}
void TournamentGui()
{
GUILayout.BeginArea(new Rect((Screen.width - 450),0,450,Screen.height));
// Title box
GUI.Box (new Rect(0, - scrollPosition.y, 100,200), "", MenuSkin.GetStyle("tournament_bar"));
GUI.Label (new Rect(121 , - scrollPosition.y, 100,200), "Tournament", MenuSkin.GetStyle("heading"));
Rect boxRect = new Rect();
if(scores != null)
{
var x = 0;
foreach(object scoreEntry in scores)
{
Dictionary<string,object> entry = (Dictionary<string,object>) scoreEntry;
Dictionary<string,object> user = (Dictionary<string,object>) entry["user"];
string name = ((string) user["name"]).Split(new char[]{' '})[0] + "\n";
string score = "Smashed: " + entry["score"];
boxRect = new Rect(0, 121+(TournamentStep*x)-scrollPosition.y , 100,128);
// Background box
GUI.Box(boxRect,"",MenuSkin.GetStyle("tournament_entry"));
// Text
GUI.Label (new Rect(24, 136 + (TournamentStep * x) - scrollPosition.y, 100,128), (x+1)+".", MenuSkin.GetStyle("tournament_position")); // Rank e.g. "1.""
GUI.Label (new Rect(250,145 + (TournamentStep * x) - scrollPosition.y, 300,100), name, MenuSkin.GetStyle("tournament_name")); // name
GUI.Label (new Rect(250,193 + (TournamentStep * x) - scrollPosition.y, 300,50), score, MenuSkin.GetStyle("tournament_score")); // score
Texture picture;
if (friendImages.TryGetValue((string) user["id"], out picture))
{
GUI.DrawTexture(new Rect(118,128+(TournamentStep*x)-scrollPosition.y,115,115), picture); // Profile picture
}
x++;
}
}
else GUI.Label (new Rect(180,270,512,200), "Loading...", MenuSkin.GetStyle("text_only"));
// Record length so we know how far we can scroll to
tournamentLength = boxRect.y + boxRect.height + scrollPosition.y;
GUILayout.EndArea();
}
// React to menu buttons //
private void onPlayClicked()
{
Util.Log("onPlayClicked");
if (friends != null && friends.Count > 0)
{
// Select a random friend and get their picture
Dictionary<string, string> friend = Util.RandomFriend(friends);
GameStateManager.FriendName = friend["first_name"];
GameStateManager.FriendID = friend["id"];
GameStateManager.CelebFriend = -1;
LoadPictureURL(friend["image_url"],FriendPictureCallback);
}
else
{
//We can't access friends
GameStateManager.CelebFriend = UnityEngine.Random.Range(0,CelebTextures.Length - 1);
GameStateManager.FriendName = CelebNames[GameStateManager.CelebFriend];
}
// Start the main game
Application.LoadLevel("GameStage");
GameStateManager.Instance.StartGame();
}
public void SetFullscreenMode (bool on)
{
if (on)
{
Screen.SetResolution (Screen.currentResolution.width, Screen.currentResolution.height, true);
}
else
{
Screen.SetResolution ((int)CanvasSize.x, (int)CanvasSize.y, false);
}
}
public static void FriendPictureCallback(Texture texture)
{
GameStateManager.FriendTexture = texture;
}
delegate void LoadPictureCallback (Texture texture);
IEnumerator LoadPictureEnumerator(string url, LoadPictureCallback callback)
{
WWW www = new WWW(url);
yield return www;
callback(www.texture);
}
void LoadPictureAPI (string url, LoadPictureCallback callback)
{
FB.API(url,Facebook.HttpMethod.GET,result =>
{
if (result.Error != null)
{
Util.LogError(result.Error);
return;
}
var imageUrl = Util.DeserializePictureURLString(result.Text);
StartCoroutine(LoadPictureEnumerator(imageUrl,callback));
});
}
void LoadPictureURL (string url, LoadPictureCallback callback)
{
StartCoroutine(LoadPictureEnumerator(url,callback));
}
void LoginCallback(FBResult result)
{
Util.Log("LoginCallback");
if (FB.IsLoggedIn)
{
OnLoggedIn();
}
}
void OnLoggedIn()
{
Util.Log("Logged in. ID: " + FB.UserId);
// Reqest player info and profile picture
FB.API("/me?fields=id,first_name,friends.limit(100).fields(first_name,id)", Facebook.HttpMethod.GET, APICallback);
LoadPicture(Util.GetPictureURL("me", 128, 128), MyPictureCallback);
}
void APICallback(FBResult result)
{
Util.Log("APICallback");
if (result.Error != null)
{
Util.LogError(result.Error);
// Let's just try again
FB.API("/me?fields=id,first_name,friends.limit(100).fields(first_name,id)", Facebook.HttpMethod.GET, APICallback);
return;
}
profile = Util.DeserializeJSONProfile(result.Text);
GameStateManager.Username = profile["first_name"];
friends = Util.DeserializeJSONFriends(result.Text);
}
void MyPictureCallback(Texture texture)
{
Util.Log("MyPictureCallback");
if (texture == null)
{
// Let's just try again
LoadPicture(Util.GetPictureURL("me", 128, 128), MyPictureCallback);
return;`
}
GameStateManager.UserTexture = texture;
}
}
change the word "LoadPicture" for "LoadPictureAPI".
For reference see:
https://github.com/fbsamples/friendsmash-unity/blob/master/friendsmash_payments_start/Assets/Scripts/MainMenu.cs
I have one problem which I cannot resolve (at least I didn't found solution yet...) I wanted to add data into IsolatedStorageSettings in WP8. My goal is to check if there are settings already in there, but when I want to check I get an exception which I cannot resolve.
private IsolatedStorageSettings appSettings = new IsolatedStorageSettings();
private void Button_Click(object sender, RoutedEventArgs e)
{
//correct this part
if (String.IsNullOrEmpty((string)appSettings["ICE1"])||
String.IsNullOrEmpty((string)appSettings["ICE2"]) ||
String.IsNullOrEmpty((string)appSettings["ICE3"]) ||
String.IsNullOrEmpty((string)appSettings["address"]) ||
String.IsNullOrEmpty((string)appSettings["fullName"]))
{
appSettings.Add("fullName", fullName.Text);
appSettings.Save();
appSettings.Add("address", address.Text);
appSettings.Save();
if (Regex.IsMatch(prefix1.Text, "^+\\d{2,3}") && Regex.IsMatch(number1.Text, "d{6,10}"))
{
appSettings.Add("ICE1", prefix1.Text + number1.Text);
appSettings.Save();
}
else
{
MessageBox.Show("Invalid prefix number, please use +01 and for numbers only 0-9...");
}
if (Regex.IsMatch(prefix2.Text, "^+\\d{2,3}") && Regex.IsMatch(number2.Text, "d{6,10}"))
{
appSettings.Add("ICE2", prefix2.Text + number2.Text);
appSettings.Save();
}
else
{
MessageBox.Show("Invalid prefix number, please use +01 and for numbers only 0-9...");
}
if (Regex.IsMatch(prefix2.Text, "^+\\d{2,3}") && Regex.IsMatch(number2.Text, "d{6,10}"))
{
appSettings.Add("ICE3", prefix2.Text + number2.Text);
appSettings.Save();
}
else
{
MessageBox.Show("Invalid prefix number, please use +01 and for numbers only 0-9...");
}
MessageBox.Show("Your information is saved...!");
}
else
{
//
appSettings["fullName"] = fullName.Text;
appSettings.Save();
appSettings["address"] = address.Text;
appSettings.Save();
if (Regex.IsMatch(prefix1.Text, "^+\\d{2,3}") && Regex.IsMatch(number1.Text, "d{6,10}"))
{
appSettings["ICE1"]= prefix1.Text + number1.Text;
appSettings.Save();
}
else
{
MessageBox.Show("Invalid prefix number, please use +01 and for numbers only 0-9...");
}
if (Regex.IsMatch(prefix2.Text, "^+\\d{2,3}") && Regex.IsMatch(number2.Text, "d{6,10}"))
{
appSettings["ICE2"] = prefix2.Text + number2.Text;
appSettings.Save();
}
else
{
MessageBox.Show("Invalid prefix number, please use +01 and for numbers only 0-9...");
}
if (Regex.IsMatch(prefix2.Text, "^+\\d{2,3}") && Regex.IsMatch(number2.Text, "d{6,10}"))
{
appSettings["ICE3"] = prefix3.Text + number3.Text;
appSettings.Save();
}
else
{
MessageBox.Show("Invalid prefix number, please use +01 and for numbers only 0-9...");
}
MessageBox.Show("Your information is saved...!");
}
Can someone explain how IsolatedStorageWorks?
How can I correct this part because this is causing the problem:
if (String.IsNullOrEmpty((string)appSettings["ICE1"])||
String.IsNullOrEmpty((string)appSettings["ICE2"]) ||
String.IsNullOrEmpty((string)appSettings["ICE3"]) ||
String.IsNullOrEmpty((string)appSettings["address"]) ||
String.IsNullOrEmpty((string)appSettings["fullName"]))
Do I need to do appSettings.Save() every each time when I wish to add the data or update-it...?
I also have another problem of getting data from IsolatedStorageSettings:
public WindowsPhoneControl2()
{
InitializeComponent();
}
string ice1;
string ice2;
string ice3;
PhoneCallTask ptask = new PhoneCallTask();
private void Image_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
ptask.PhoneNumber = ice1;
ptask.DisplayName = "Contact person 1";
ptask.Show();
}
private void Image_Tap_1(object sender, System.Windows.Input.GestureEventArgs e)
{
ptask.PhoneNumber = ice2;
ptask.DisplayName = "Contact person 2";
ptask.Show();
}
private void Image_Tap_2(object sender, System.Windows.Input.GestureEventArgs e)
{
ptask.PhoneNumber = ice3;
ptask.DisplayName = "Contact person 3";
ptask.Show();
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
IsolatedStorageSettings appSettings = IsolatedStorageSettings.ApplicationSettings;
appSettings.Contains("fullName");
fullName.Text = (string)appSettings["fullName"];
address.Text = (string)appSettings["address"];
phone1.Text = (string)appSettings["ICE1"];
phone2.Text = (string)appSettings["ICE1"];
phone3.Text = (string)appSettings["ICE1"];
ice1 = phone1.Text;
ice2 = phone2.Text;
ice3 = phone3.Text;
}
especially this part which is supposed to get data from dictionary:
fullName.Text = (string)appSettings["fullName"];
address.Text = (string)appSettings["address"];
phone1.Text = (string)appSettings["ICE1"];
phone2.Text = (string)appSettings["ICE1"];
phone3.Text = (string)appSettings["ICE1"];
IsolatedStorage Settins works like a dictionary.
I think you should change:
private IsolatedStorageSettings userSettings = IsolatedStorageSettings.ApplicationSettings;
I would rather use method Contains to check whether key is there:
if (userSettings.Contains("ICE1")||
userSettings.Contains("ICE2") ||
userSettings.Contains("ICE3") ||
userSettings.Contains("address") ||
userSettings.Contains("fullName"))
According to MSDN, Settings are saved when the Application is closed or you call Save:
Data written to the IsolatedStorageSettings object is saved when the application that
uses the class is closed. If you want your application to write to isolated storage
immediately, you can call the Save method in application code.
EDIT
Sample code to play with:
public partial class MainPage : PhoneApplicationPage
{
private IsolatedStorageSettings userSettings = IsolatedStorageSettings.ApplicationSettings;
public MainPage()
{
InitializeComponent();
bool isKey = userSettings.Contains("anyKey"); //toggle break point at this line
userSettings.Add("anyKey", "myValue");
isKey = userSettings.Contains("anyKey");
string value = (string)userSettings["anyKey"];
}
}
IsolatedStorageSetting stores data in key/value pair. If there exist a key there must would be a value regarding this key. so just simpley check whether key exist in setting or not using if(settings.Contains("YourKey")). If the condition true do your work. Thanks