Play game saves ((PlayGamesPlatform)Social.Active).SavedGame.OpenWithAutomaticConflictResolution doesn't invoke save function - unity3d

Good day!
I am new to Google Play Services and want to save JSON(string) into the cloud and it doesn't work. I narrowed down a problem through phone and debug texts and realized that a function from ((PlayGamesPlatform)Social.Active).SavedGame.OpenWithAutomaticConflictResolution is not called which is strange because in the tutorial that I watched everything worked and the user logged in successfuly.
here is a code snippet with a comments and a function that is not invoked(I can send a whole script if needed also). Is there something else I am missing?
public void OpenSaveToCloud(bool saving)
{
// debugtext.text = "hello";
if(Social.localUser.authenticated)
{
debugtext.text = "Authorized and proceed to save";
issaving = saving;
((PlayGamesPlatform)Social.Active).SavedGame.OpenWithAutomaticConflictResolution
(SAVE_NAME, GooglePlayGames.BasicApi.DataSource.ReadCacheOrNetwork,
ConflictResolutionStrategy.UseLongestPlaytime, SavedGameOpen); //SavedGame open must be called
}
else{
debugtext.text = "No authentication";
}
}
private void SavedGameOpen(SavedGameRequestStatus status, ISavedGameMetadata meta)//this function is not called
{
if(status == SavedGameRequestStatus.Success)
{
// debugtext.text = "hello in save1";
if (issaving)//if is saving is true we are saving our data to cloud
{
debugtext.text = "Saving....";
byte[] data = System.Text.ASCIIEncoding.ASCII.GetBytes(GetDataToStoreinCloud());
SavedGameMetadataUpdate update = new SavedGameMetadataUpdate.Builder().Build();
((PlayGamesPlatform)Social.Active).SavedGame.CommitUpdate(meta, update, data, SaveUpdate);
}
else//if is saving is false we are opening our saved data from cloud
{
debugtext.text = "Loading...";
((PlayGamesPlatform)Social.Active).SavedGame.ReadBinaryData(meta, ReadDataFromCloud);
}
}
else{
debugtext.text = "Save request status broke";
}
}
What I checked twice before posting question:
Turned on Saved Games in google console
made build with your keystore and password
add email id in game service's tester section

Mistake is that you have to initialize save games from start as well and I didn't know that so answer would be
if (platform == null)
{
PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder().EnableSavedGames().Build();
PlayGamesPlatform.InitializeInstance(config);
PlayGamesPlatform.DebugLogEnabled = true;
platform = PlayGamesPlatform.Activate();
}

Related

Can two ASP . NET Core 5.0 web api cause "The content may be already have been read by another component" errpr 400 if they accessed same db be4?

My API was as follows:
[HttpPut("{id}")]
public async Task<ActionResult<HomeContextModel>> EditHomeContext(int id, string title, string context, string subcontext, IFormFile imageFile)
{
HomeContextModel homeContextModel = await _context.HomeContext.Include(x => x.Image).Include(x => x.Button).Include(x => x.Logo).ThenInclude(y => y.Image)
.FirstOrDefaultAsync(m => m.Context_Id == id);
//HomeContextModel homeContextModel = await GetHomeContextModel(id);
if (homeContextModel == null)
{
return BadRequest("Context Id cannot be null");
}
if (imageFile != null)
{
ImageModel imageModel = homeContextModel.Image;
if (imageModel != null)
{
string cloudDomain = "https://privacy-web.conveyor.cloud";
string uploadPath = _webHostEnvironment.WebRootPath + "\\Images\\";
if (!Directory.Exists(uploadPath))
{
Directory.CreateDirectory(uploadPath);
}
string filePath = uploadPath + imageFile.FileName;
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
await imageFile.CopyToAsync(fileStream);
await fileStream.FlushAsync();
}
using (var memoryStream = new MemoryStream())
{
await imageFile.CopyToAsync(memoryStream);
imageModel.Image_Byte = memoryStream.ToArray();
}
imageModel.ImagePath = cloudDomain + "/Images/" + imageFile.FileName;
imageModel.Modify_By = "CMS Admin";
imageModel.Modity_dt = DateTime.Now;
//_context.Update(imageModel);
}
}
homeContextModel.Title = title;
homeContextModel.Context = context;
homeContextModel.SubContext = subcontext;
_context.Entry(homeContextModel).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!HomeContextModelExists(homeContextModel.Context_Id))
{
return NotFound();
}
else
{
throw;
}
}
return Ok("Home Context Edit Successfully");
}
It's an API for the Content Management System (CMS) to change the content of the Homepage using a Flutter webpage that make put request onto this API.
Everything works fine. In the last few days, where I tested and tested again during the development. So before today, I've wrapped up them and submitted to the necessary place (It's a university FYP).
Until now it cause me this error when I was using this to prepare my presentation:
Error 400 failed to read the request form Unexpected end of stream ..."
After all the tested I tried:
Internet solutions
restore the database
repair Microsoft VS 2019 (As this issue was fixed before after I
updated my VS 2019 from 16.8. to the latest 16.11.7)
Use the ASP .NET file which didn't caused this issue before
Then I realized it may be because of I used another older ASP file to accessed the same database before. Does this really cause this matter?
If yes, then now how should I solved it, with the action I already done (listed as above)?
EDIT: Additional description to the situation
The above API I set breakpoint before, on the first line, using Swagger to test it.
It turns out that it didn't go into the API and straightaway return the error 400
REST API can have parameters in at least two ways:
As part of the URL-path
(i.e. /api/resource/parametervalue)
As a query argument
(i.e. /api/resource?parameter=value)
You are passing your parameters as a query instead of a path as indicated in your code. And that is why it is not executing your code and returning 400.

how to Combine between playfab and photon friend's info

I am using pun 2 and playfab. I did that every time you add a new friend it adds him to a playfab list, this is good because I can add a friend in any time, not like pun 2 but I can't see if friends are online and get the friends room name(photon option). the problem is that I convert from playfab to photon. is there a way to do it?
here is my playfab code
private void DisplayPlayfabFriends(List<PlayFab.ClientModels.FriendInfo> friendCache)
{
foreach (PlayFab.ClientModels.FriendInfo f in friendCache)
{
bool isfound = false;
if(myfriends != null)
{
foreach (PlayFab.ClientModels.FriendInfo g in myfriends)
{
if (f.FriendPlayFabId == g.FriendPlayFabId)
{
isfound = true;
}
}
}
if(isfound == false)
{
UIFriend listing = Instantiate(uiPrefab, container);
if(listing != null)
{
listing.Initialize(f);
listing.friendNameText.text = f.TitleDisplayName;
}
}
}
myfriends = friendCache;
}
here is the photon code
public void Initialize(Photon.Realtime.FriendInfo friendInfo)
{
info = friendInfo;
roomName = $"{infophoton.UserId}";
friendNameText.text = $"{info.UserId}";
if (infophoton.IsOnline)
{
onlineImage.color = onlineColor;
}
else
{
onlineImage.color = offlineColor;
}
}
how to Combine between them both?
I replied on the official Photon forum here.
Quoting my reply:
Assuming you use the PlayFab integration with Photon as we recommend
it, Photon UserID and PlayFab ID will be the same. So you can cache
friends in a dictionary with keys set to their FriendID which is the
Photon UserID / PlayFab ID and as values create a new class that
combines info from PlayFab's FriendInfo and Photon's FriendInfo. Then
periodically call PlayFab's GetFriends, inside its callback update the
cached list of friends AND call Photon's FindFriends (when applicable
/ outside of rooms). In the callback of FindFriends update the cached
friends' list and update the UI.

Active Directory Authentication Library (ADAL) in an MVVM Phone 8.1 App

I am currently trying to convert the phone sample app from the official ADAL github repo to a caliburn.micro MVVM app. But there are so many moving parts backed into the code-behind to get along with WebAuthenticationBroker that I don't now how to push that into viewmodels and handle navigation correctly when the app is activated again after the broker did the sign-on. Since I am totally clueless at the moment there is no code to share yet.
I've been using MvvmLight along with ADAL in my Windows Phone 8.1 App. What you need to do is as soon as you get a token, you need to send the message using the Messenger pattern. All of those view models which require the token and have already subscribed to it will receive it. Here is something I've done in my app using MvvmLight. Remember that you need to have a ContinuationManager class and IWebContinuable interface to make the app work.
private async void Login()
{
AuthenticationResult result = null;
context = AuthenticationContext.CreateAsync("https://login.windows.net/<tenant-id>").GetResults();
try
{
//try to check if you can get the token without showing pop-up
result = await context.AcquireTokenSilentAsync("https://management.core.windows.net/", "<clientid>");
if(result.Status==AuthenticationStatus.ClientError)
{
bool exists = CheckInVault();
if(exists)
{
PasswordVault vault = new PasswordVault();
var tokenvault = vault.FindAllByResource("Token");
string RefreshToken = tokenvault[0].Password;
var refresh=await context.AcquireTokenByRefreshTokenAsync(RefreshToken, clientid);
vault.Remove(tokenvault[0]);
StoreToken(refresh);
}
else
{
context.AcquireTokenAndContinue("https://management.core.windows.net/", clientid, WebAuthenticationBroker.GetCurrentApplicationCallbackUri(), StoreToken);
}
}
else if(result != null && result.Status == AuthenticationStatus.Success)
{
// A token was successfully retrieved. Post the new To Do item
bool exists = CheckInVault();
if (exists)
{
PasswordVault vault = new PasswordVault();
var tokenvault = vault.FindAllByResource("Token");
vault.Remove(tokenvault[0]);
}
StoreToken(result);
}
//this method will be called when app is opened first time and pop-up appears
result=await context.AcquireTokenSilentAsync("https://management.core.windows.net/", "<client-id>");
}
catch(Exception e)
{
MessageDialog dialog = new MessageDialog("Error");
}
}
What I am doing here is - after acquiring the access token and reference token when the user signs up first, I store the refresh token in the PasswordVault, so as to get it in the future to enable single sign-on. ADAL actually does using its caching feature, but sometimes the single sign-on failed for me, hence using the PasswordVault to store the refresh token. After the authentication completes, I have a delegate to StoreToken function, where I actually store the new refresh token and send the access token to all the subscribers using the Messenger class in MvvmLight.
private void StoreToken(AuthenticationResult result)
{
try
{
var token = result.AccessToken;
Messenger.Default.Send<string>(token); //send the access token.
PasswordVault vault = new PasswordVault();
PasswordCredential credential = new PasswordCredential();
credential.UserName = result.AccessToken;
credential.Password = result.RefreshToken;
credential.Resource = "Token";
vault.Add(credential);
}
catch(Exception e)
{
}
}
I would recommend handling the navigation in the view models. Define a helper class like NavigationService:
public class NavigationService:INavigationService
{
private Frame _frame;
public Frame Frame
{
get
{
return _frame;
}
set
{
_frame = value;
_frame.Navigated+= OnFrameNavigated;
}
}
public void NavigateTo(string type)
{
Frame.Navigate(Type.GetType(type));
}
public void GoForward()
{
if (Frame.CanGoForward)
Frame.GoForward();
}
public void GoBack()
{
if (Frame.CanGoBack)
Frame.GoBack();
}
}
To navigate to a page from the view models, you use the NavigateTo(string) method as
NavigateTo("<fully qualified class name of the page you want to navigate to>,<assembly name>")
I would also suggest using a IoC container (MvvmLight gives you a ViewModelLocator class) so that you can maintain singleton instances of your view models and helpers like NavigationService. I haven't used the CaliburnMicro framework but I would assume there would be similar features for Messaging and Dependency Injection.

Facebook profile picture doesnt show up, it shows an icon of a question mark

Do you have any idea? I am developing an app using Unity IDE and C#. Also, I'm using the social networking prime31 for my plugin with Facebook. I was able to get all the graphs and display it in my screen app, but since last week it didn't show the profile picture and my friend's picture, it just shows a plain question mark. Do you have any idea with regard to that?
But I was able to show the username and my friend's username. My app token is working, and I am using JSON data to get the data from the Facebook URL.
void Start()
{
getFB_ID();
}
void getFB_ID()
{
Facebook.instance.graphRequest( "me/", HTTPVerb.GET, ( error, obj ) =>
{
var ht = obj as Hashtable;
userId = ht["id"].ToString();
Debug.Log( "USER ID: " + userId);
string url = "http://graph.facebook.com/"+userId+"?fields=id,name,picture";
StartCoroutine(getURL(url));
});
}
IEnumerator getURL(string url)
{
WWW www = new WWW(url);
yield return www;
Debug.Log ("Heres the URL you are accessing: " + url);
ProfilePicDisplay(www.text);
public void ProfilePicDisplay(string jsonString)
{
JsonData jsonProfilePic = JsonMapper.ToObject(jsonString);
ConverterScript fbprofilepic;
MyPicture = new ArrayList();
{
fbprofilepic = new ConverterScript();
fbprofilepic.name = jsonProfilePic["name"].ToString();
fbprofilepic.picture = jsonProfilePic["picture"].ToString();
LoadProfilePic(fbprofilepic);
MyPicture.Add(fbprofilepic.name);
}
}
private void LoadProfilePic(ConverterScript profile)
{
string ProfilePic = "userAvatar";
GameObject profile_pic_holder = GameObject.Find(ProfilePic);
profile_pic_holder.SendMessage("LoadImage", profile);
}
was able to get the data in my logs, but the problem is it didnt load the image, it says:
You are trying to load data from a www stream which had the following error when downloading.
Could not resolve host: JsonData object (Domain name not found)
As of last week, October 3rd and detailed here: https://developers.facebook.com/blog/post/2012/10/03/platform-updates--operation-developer-love/
The picture endpoint no longer returns the picture URL in the string. It returns a dictionary and you have to change your parsing to get to it. So the data returned will look more like this:
{
"id": "1234567",
"name": "Your Name",
"picture": {
"data": {
"url": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-prn1/your_picture.jpg",
"is_silhouette": false
}
}
}
In the latest LeanLoader, there is an automatic fix for the newly implimented Facebook endpoint abernathy mentioned, which allows you to load the image directly (with all the parsing of the json and other data handled by the engine). You can easily load profile images like this:
function Start () {
LeanLoader.load("https://graph.facebook.com/DentedPixel/picture?type=large&redirect=false", LLOptions().setOnLoad(onImageLoaded));
}
private function onImageLoaded( tex:Texture2D ){
Debug.Log("Your image texture ready to use! :"+tex);
}
There is also many other features that I think people will find helpful with LeanLoader (including caching of images/text/sound and a built-in JSON parser).
try this- fb sdk version-9.1.0
FB.API ("/me/picture?type=large", HttpMethod.GET, DisplayProfilePic);// API call
void DisplayProfilePic(IGraphResult result)
{
Image profilePic;
if (result.Texture != null)
{
profilePic = image1; // diplaying image
profilePic.sprite = Sprite.Create(result.Texture, new Rect(0, 0, result.Texture.width, result.Texture.height), new Vector2());
}
}

How to get alerts from action in asp.net mvc

as far as I know we can not call the javascript method in controller's action method. but how to consider that a particular code line get executed ? As i asked earlier here
we must have to get acknowledgment that line number so and so get executed. see this action in my controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult uploadfile(FormCollection fc)
{
UserMaster objUMaster = objAM.GetUser(new Guid(fc["userIdForFile"].ToString()));
try
{
string imagename = "";
//Check for files uploaded here.
foreach (string inputTagName in Request.Files)
{
HttpPostedFileBase file = Request.Files[inputTagName];
imagename = objUMaster.UserId.ToString() + file.FileName;
if (file.ContentLength > 0)
{
string filePath = Path.Combine(HttpContext.Server.MapPath("../Content/UserUploads"), objUMaster.UserId.ToString() + Path.GetFileName(file.FileName));
file.SaveAs(filePath);
string filePathThumb = Path.Combine(HttpContext.Server.MapPath("../Content/UserUploads/Thumbnails"), objUMaster.UserId.ToString() + Path.GetFileName(file.FileName));
var fl = Request.Files.Get(inputTagName);
Stream strm = fl.InputStream;
Image img = Image.FromStream(strm);
ResizeAndSaveHighQualityImage(img, 120, 120, filePathThumb, 100);
}
}
objUMaster.ProfilePhoto = imagename;
objAM.Save();
return RedirectToAction("EditProfile", new { id = objUMaster.UserId });
}
catch (Exception ex)
{
//SendEmail(ex.Message);
string strPath = HttpContext.Server.MapPath("../Content/UserUploads");
StreamWriter SW;
SW = System.IO.File.CreateText(strPath+"/log.txt");
SW.WriteLine(ex.Message.ToString());
SW.Close();
return RedirectToAction("EditProfile", new { id = objUMaster.UserId });
}
}
Here I am trying to upload the image in my domains file system (dir). but I want get alert so that I can confirm , this lie get executed successfully. because nothing happening as expected from this action. so can we call Javascript's "alert", or something else remedy?
Some pointers to help you:
See if Network service/account under which your application is running has permission on the location where you are saving your file.
Besides this to make sure that your file is saved, after save call you can make another call File.IsExist. If it exists then you can log the success/failure in some log file. Wouldn't that work for you?