So I am trying to post to my web api and use a callback when the post finishes. This all works perfectly in the Unity editor and as a Desktop app, but does NOT work in the Web Player. I have narrowed it down to just the callback not actually getting called. How can I use callbacks? Here is my code:
void ui_login() {
if (uiBase == null)
return;
Debug.LogError(uiBase); clicks++; status = "(" + clicks + ")" + "working";
var username = uiBase.UIElements.FirstOrDefault(e => e.Name == "txt_username");
var password = uiBase.UIElements.FirstOrDefault(e => e.Name == "txt_password");
try
{
var request = new LoginRequest()
{
Email = username.Text,
Password = password.Text
};
StartCoroutine(WaitForRequest<LoginResponse>(request, loginCallback));
}
catch (Exception e)
{
status = "(" + clicks + ")" + e;
}
}
void loginCallback(LoginResponse response, WWW www)
{
if (www.error != null)
status = www.error;
if (response != null)
status = response.ErrorMessage;
}
IEnumerator WaitForRequest<TResponse>(
LoginRequest request, Action<TResponse, WWW> callback)
{
var json = JsonMapper.ToJson(request);
var www = new WWW("http://someurl.com", json.ToBytes());
yield return www;
TResponse response;
if (www.error == null && www.isDone)
{
var str = Encoding.UTF8.GetString(www.bytes);
print(str);
status = str;
response = JsonConvert.DeserializeObject<TResponse>(str);
}
else
response = default(TResponse);
print("somthif");
callback(response, www);
}
For security reasons, Unity Web Player works in a Sandbox and will block your HTTP requests.
To fix this issue, follow the process described in this link: http://docs.unity3d.com/Documentation/Manual/SecuritySandbox.html
Related
I want to generate a shorten dynamic link from a long dynamic link
I followed the steps shown here: https://firebase.google.com/docs/dynamic-links/unity/create
yet I get the same long URL when shortening process is completed.
public void CreateInviteLink()
{
var components = new Firebase.DynamicLinks.DynamicLinkComponents(
// The base Link.
new System.Uri("https://myapp.com"),
// The dynamic link URI prefix.
"https://myapp.page.link")
{
IOSParameters = new Firebase.DynamicLinks.IOSParameters("com.myapp.myapp"),
AndroidParameters = new Firebase.DynamicLinks.AndroidParameters("com.myapp.myApp"),
};
Debug.Log("Long Dynamic Link: " + components.LongDynamicLink);
var options = new Firebase.DynamicLinks.DynamicLinkOptions
{
PathLength = DynamicLinkPathLength.Unguessable
};
Firebase.DynamicLinks.DynamicLinks.GetShortLinkAsync(components, options).ContinueWith(task => {
if (task.IsCanceled)
{
Debug.LogError("GetShortLinkAsync was canceled.");
return;
}
if (task.IsFaulted)
{
Debug.LogError("GetShortLinkAsync encountered an error: " + task.Exception);
return;
}
// Short Link has been created.
Firebase.DynamicLinks.ShortDynamicLink link = task.Result;
Debug.LogFormat("Generated Short Dynamic Link: {0}", link.Url);
text.text = link.Url.ToString();
var warnings = new System.Collections.Generic.List<string>(link.Warnings);
if (warnings.Count > 0)
{
// Debug logging for warnings generating the short link.
}
});
}
result Logs
Long Dynamic Link: https://myapp.page.link/?afl=&amv=0&apn=com.myapp.myApp&ibi=com.myapp.myapp&ifl=&ipfl=&link=https://myapp.com
UnityEngine.Debug:Log(Object)
Generated Short Dynamic Link: https://myapp.page.link/?afl=&amv=0&apn=com.myapp.myApp&ibi=com.myapp.myapp&ifl=&ipfl=&link=https://myapp.com
UnityEngine.Debug:LogFormat(String, Object[])
EDIT:
How I did it:
You can't shorten dynamic links with Firebase SDK in the editor but I used REST API and UnityWebRequest for testing short links inside the editor and it worked
IEnumerator HTTPRequestShortLink(string longDynamicLink)
{
WWWForm form = new WWWForm();
form.AddField("longDynamicLink", longDynamicLink);
// trigger of function is HTTP request. this link is the trigger for that func
UnityWebRequest www = UnityWebRequest.Post("https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=[YOUR_API_KEY]", form);
//for getting response
www.downloadHandler = new DownloadHandlerBuffer();
yield return www.SendWebRequest();
if (www.result != UnityWebRequest.Result.Success)
{
Debug.Log(www.error);
}
else
{
Debug.Log("Form upload complete! " + www.GetResponseHeader("response"));
string responseText = www.downloadHandler.text;
// Parse returned json
parsedJsonObject obj = parsedJsonObject.CreateFromJSON(responseText);
Debug.Log("shortLink: " + obj.shortLink);
Debug.Log("HTTP Response text: " + responseText);
}
}
I am developing telegram notifications in my existing asp.net core 3.1 project. I have written below code in controller.
#region Telegram
TelegramBotClient _botService;
private const string token = "332435:45345345345dflskdfjksdjskdjflkdd";
[HttpPost("Update")]
[AllowAnonymous]
public async Task<IActionResult> Update([FromBody] Update update)
{
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
if (_botService == null)
_botService = new TelegramBotClient(token);
if (update.Type != UpdateType.Message)
return Ok(new Response
{
code = (int)HttpStatusCode.OK,
status = "Ok",
message = "Success"
});
var message = update.Message;
try
{
_logger.LogInformation("Received Message from {0}", message.Chat.Id);
switch (message.Type)
{
case MessageType.Text:
if (message.Text.Contains("/Reset"))
{
//Delete(string chatid)
var response = _UserRepository.DeleteTeleBotChatID(message.Chat.Id);
if (response)
await _botService.SendTextMessageAsync(message.Chat.Id, "You have successfully unsubscribed.");
else
await _botService.SendTextMessageAsync(message.Chat.Id, "You are not registered yet.");
}
else
if (message.Text.Contains("/") && !message.Text.ToLower().Contains("/start"))
{
var user = Crypto.decrypt(Encoding.UTF8.GetString(Convert.FromBase64String(message.Text.Split('/').Last())));
var response = _UserRepository.UpdateTeleBotChatIDByUser(new TeleBotModel() { ChatId = message.Chat.Id, Username = user });
if (response)
await _botService.SendTextMessageAsync(message.Chat.Id, $"You have successfully subscribe notifications for {user}.");
else
await _botService.SendTextMessageAsync(message.Chat.Id, "Username is not valid");
// var chat=modifyus(string username,chatid)
}
else
{
await _botService.SendTextMessageAsync(message.Chat.Id, "Enter your encrypted username.\n Type /Reset to unsubscribe.");
}
break;
case MessageType.Photo:
// Download Photo
var fileId = message.Photo.LastOrDefault()?.FileId;
var file = await _botService.GetFileAsync(fileId);
var filename = file.FileId + "." + file.FilePath.Split('.').Last();
using (var saveImageStream = System.IO.File.Open(filename, FileMode.Create))
{
await _botService.DownloadFileAsync(file.FilePath, saveImageStream);
}
await _botService.SendTextMessageAsync(message.Chat.Id, "Thx for the Pics");
break;
}
}
catch (Exception exp)
{
//LoggerSimple.Error(exp);
await _botService.SendTextMessageAsync(message.Chat.Id, "Wrong Bot command");
}
return Ok(new Response
{
code = (int)HttpStatusCode.OK,
status = "Ok",
message = "Success"
});
}
[HttpPost]
public async Task<IActionResult> sendTeleMsg(TelegramMessgae Data)
{
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
if (_botService == null)
_botService = new TelegramBotClient(token);
//check username exist
long ChatId = _UserRepository.GetChatIdByUsername(Data.Username);
if (ChatId == -1)
{
return Ok(new Response
{
error = "true",
code = HttpStatusCode.BadRequest,
status = HttpStatus.OK,
message = "Not registered with telegram bot"
});
}
try
{
await _botService.SendTextMessageAsync(ChatId, string.Format("*{0}*\n{1}", parseMText(Data.Subject), parseMText(Data.Message)), ParseMode.Markdown);
return Ok(new Response
{
code = HttpStatusCode.OK,
status = HttpStatus.OK,
message = "Message Sent"
});
}
catch (Exception exp)
{
//if wrong chatid
_UserRepository.DeleteTeleBotChatID(ChatId);
return Ok(new Response
{
error = "true",
code = HttpStatusCode.BadRequest,
status = HttpStatus.OK,
message = exp.Message
});
}
}
private string parseMText(string txt)
{
var vs = new string[] { "*", "_", "`", "[", "]" };
foreach (var item in vs)
{
txt = txt.Replace(item, "\\" + item);
}
return txt;
}
#endregion
then used ngrok for tunnelling and exposed localhost so that I can connect with telegram bot. After creating and subscribing the bot, I am able to receive a breakpoint in above Update method but data was nothing. I sent messages on bot but always there is no data in update object. See below screenshot.
I am unable to figure-out the issue in the code. Can anyone pls help?
Calling AddNewtonsoftJson() function in starup.cs file fixed the issue.
services.AddControllers().AddNewtonsoftJson();
I'm having an issue with sending a POST request for Pinterest in a UWP app I'm working on. I already have the access code from a previous WebAuthenticationBroker function. I've tried using the WebAuthenticationBroker with the UseHttpPost option under options with authenticating async, but, as I've provided my if functions, it returns ERROR. I just get a "message": "405: Method Not Allowed" and "type" : "http". I've looked all over, I've even tried using an HttpClient and PostAsync(), but I couldn't get it to get the access token. Any advise to what I'm doing wrong?
private void OutputToken(string TokenUri)
{
int tokenString = TokenUri.IndexOf('=');
string TheTokenUri = TokenUri.Substring(tokenString + 54);
PinterestReturnedTokenText.Text = TheTokenUri;
outputToken = TheTokenUri;
}
private async void auth()
{
try
{
string CallbackUrl = "https://localhost/";
string PinterestUrl = "https://api.pinterest.com/v1/oauth/token?grant_type=authorization_code&client_id=" + PinterestClientID + "&client_secret=" + PinterestClientSecret + "&code=" + outputCode;
Uri StartUri = new Uri(PinterestUrl);
Uri EndUri = new Uri(CallbackUrl);
WebAuthenticationResult WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.UseHttpPost, StartUri, EndUri);
if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
{
OutputToken(WebAuthenticationResult.ResponseData.ToString());
await GetPinterestNameAsync(WebAuthenticationResult.ResponseData.ToString());
}
else if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
{
OutputToken("HTTP Error returned by AuthenticateAsync() : " + WebAuthenticationResult.ResponseErrorDetail.ToString());
}
else
{
OutputToken("Error returned by AuthenticateAsync() : " + WebAuthenticationResult.ResponseStatus.ToString());
}
}
catch (Exception Error)
{
PinterestReturnedTokenText.Text = "ERROR";
}
}
At present, I was facing some sort of weird problem. I turn off my internet connection to put some handling code over their. I thought it will return me some error code but its just giving me blank response rather than showing exception. I got following debug output when I print more details on screen.
Basically I want to show dialog box when there is no internet connection. But how to handle this situation!!!
Because there is no json response from server side then also there is some bytes I am receiving from server. Here is my code:
Dictionary<string,string> headerDisc = new Dictionary<string, string> ();
headerDisc.Add ("Api-Key", "You API Key");
WWW www = new WWW (GameConstants.CONTESTANT_LIST_BASE_URL, new byte[] { (byte)0 }, headerDisc);
yield return www;
if (www.error == null) {
Debug.Log ("bytes: " + www.bytes.Length);
Debug.Log ("size: " + www.size);
Debug.Log ("length: " + www.text.Length);
Debug.Log ("Data: " + www.text);
if (www.text.Length <= 0) {
AppManager.Instance.DialogMessage = "No Server Response Found!";
Camera.main.SendMessage ("ActivateDialogBoxPanel", true, SendMessageOptions.DontRequireReceiver);
} else {
JSONObject jsonObj = new JSONObject (www.text);
JSONObject messageObj = jsonObj [TAG_MESSAGE];
string successValueStr = jsonObj [TAG_SUCCESS].ToString ();
if (successValueStr.Equals (VALUE_TRUE))
// success
else
// fail
}
} else {
Debug.Log ("Error: " + www.error);
AppManager.Instance.DialogMessage = "Error:" + www.error;
Camera.main.SendMessage ("ActivateDialogBoxPanel", true, SendMessageOptions.DontRequireReceiver);
}
Please give me some suggestion in this. If you want some more information then I am available.
As i understand you want to check if internet connection is disabled show a message to user . for example you can write something like this.
IEnumerator checkInternetConnection(Action<bool> action){
WWW www = new WWW("http://google.com");
yield return www;
if (www.error != null) {
action (false);
} else {
action (true);
}
}
then in your Start() function write this.
void Start(){
StartCoroutine(checkInternetConnection((isConnected)=>{
// handle connection status here
}));
}
I have the following code which creates a Task in Salesforce and then tracks a user's browsing history and stores it in SalesForce. Currently, it displays each and every page the user has browsed as an individual entry. I want to group all those entries together in the Browsing_History__c object instead of task being created every time a user visits a page.
Any help would be appreciated..I am not familiar with SF very much. :)
private void CreateTaskInSF(string id, string type, string details, string description)
{
// if there's a similar Event in the past 2 hours, don't add it
QueryResult qr = null;
try // get events from past 2 hours
{
qr = Binding.query("Select Details__c from Task WHERE WhoId='" + id + "' and Type__c='" + type + "' and CreatedDate > " + DateTime.UtcNow.AddHours(-2).ToString("s") + "Z");
}
catch (Exception e)
{
return;
}
bool logged = false;
if (qr != null) // if there are Tasks in past 2 hours
{
sforce.sObject[] browsing = qr.records;
if (browsing != null)
{
// iterate through events to make sure the new Task isn't logged
for (int i = 0; i < browsing.Length; i++)
{
Task currTask = (Task)browsing[i];
if (currTask.Details__c == details)
{
if (description != "") // is there a description to check for?
{
string oldTaskDescription = "";
if (currTask.Description != null)
oldTaskDescription = currTask.Description;
if (oldTaskDescription == description) // if there is a description match
logged = true;
}
else
logged = true; // there's no description, so check only on details field
}
}
}
}
if (logged == true)
{
return; // if Activity is already logged, don't log it again
}
else if (type == "Browsing")
{
QueryResult browsingQuery = null;
try // get events from past 2 hours
{
browsingQuery = Binding.query("Select Web_Browsing__c from Task WHERE WhoId='" + id + "' and Subject='" + type + "' and Details__c='" + details + "' and CreatedDate > " + DateTime.UtcNow.AddHours(-2).ToString("s") + "Z");
}
catch
{
}
Boolean createNewBrowsing = false;
if (browsingQuery != null) // if there are Tasks in past 2 hours
{
sforce.sObject[] webBrowsing = browsingQuery.records;
if (webBrowsing != null)
{
//find correct object and update Browsing_History__c
//Binding.update
}
else
{
createNewBrowsing = true;
}
}
else
{
createNewBrowsing = true;
}
if (createNewBrowsing)
{
Web_Browsing__c newTask = new Web_Browsing__c();
newTask.Lead__c = id;
newTask.Browsing_History_255__c = details;
newTask.Type__c = type;
newTask.Browsing_History__c = details;
newTask.CreatedDate = DateTime.Now;
//if(type == "Browsing") newTask. = details;
//SaveResult[] createResult = Binding.create(new sObject[] { newTask });
try
{
SaveResult[] createResult = Binding.create(new sObject[] { newTask });
}
catch (Exception e)
{
return;
}
}
}
else
{
// if this new Activity isn't logged, then create a new Activity Task
sforce.Task newTask = new sforce.Task();
newTask.WhoId = id;
newTask.Subject = type;
newTask.Details__c = details;
if (description != "") newTask.Description = description;
newTask.Status = "Completed";
newTask.Priority = "Normal";
newTask.ActivityDate = DateTime.Now;
newTask.ActivityDateSpecified = true;
// insert it
try
{
SaveResult[] createResult = Binding.create(new sforce.sObject[] { newTask });
}
catch (Exception e)
{
return;
}
}
}
You'll need to update your query to ask for the browsing history object and update the code to create a browsing history object instead of a task.
If you haven't already, review the Web Services API docs, it has examples for querying and creating in java/c#.