Unity WebGL - accessing StreamingAssets folder from build uploaded in LMS /Server - unity3d

I couldn't access the files StreamingAssets folder from WebGL build which is uploaded in LMS server, I kept those files in StreamingAssets folder to update it for future use. Followed the instruction given in unity manual, working fine in editor, but with direct build run and in LMS its not working.
http://docs.unity3d.com/ScriptReference/Application-streamingAssetsPath.html
Posted in forums, they ask to follow the manual, but its not working. Please find the script attached here for more details. Check the coroutine function named ' userDetailsXmlPath ' which called at start of the game.
public string filePath = Application.streamingAssetsPath + "/UserDetails.xml";
public string result = "";
IEnumerator userDetailsXmlPath()
{
print (filePath);
if (filePath.Contains ("://") || filePath.Contains (":///")) {
WWW www = new WWW (filePath);
yield return www;
result = www.text;
print (result);
FetchUserDetails ();
} else {
result = File.ReadAllText (filePath);
print (result);
FetchUserDetails ();
}
}
public void FetchUserDetails()
{
XmlDocument userXml1 = new XmlDocument ();
// userXml1.Load(Application.streamingAssetsPath + "/UserDetails.xml");
// userXml1.Load(Application.dataPath + "js/UserDetails 1.xml");
// userXml1.LoadXml(userXml.text);
userXml1.LoadXml(result);
XmlNodeList userList = userXml1.GetElementsByTagName ("user");
foreach(XmlNode userValue in userList)
{
XmlNodeList userContent = userValue.ChildNodes;
objUser = new Dictionary<string, string>();
foreach(XmlNode value in userContent)
{
objUser.Add (value.Name, value.InnerText);
}
userFullDetails.Add (objUser);
userCountInXml = userList.Count;
userId = new string[userList.Count];
questionSetOfUser = new string[userList.Count];
}
AssignUserXmlValuesToArray ();
}
Please guild me to resolve this issue.

Access StreamingAssets path folder using WWW class https://docs.unity3d.com/ScriptReference/Application-streamingAssetsPath.html
public string filePath = Application.streamingAssetsPath + "/UserDetails.xml";
public string result = "";
void Awake ()
{
filePath = Application.streamingAssetsPath + "/UserDetails.xml";
}
void Start ()
{
StartCoroutine(userDetailsXmlPath() );
}
IEnumerator userDetailsXmlPath()
{
print (filePath);
if (filePath.Contains ("://") || filePath.Contains (":///")) {
WWW www = new WWW (filePath);
yield return www;
result = www.text;
print (result);
FetchUserDetails ();
} else {
result = File.ReadAllText (filePath);
print (result);
FetchUserDetails ();
}
}
public void FetchUserDetails()
{
XmlDocument userXml1 = new XmlDocument ();
userXml1.LoadXml(result);
XmlNodeList userList = userXml1.GetElementsByTagName ("user");
foreach(XmlNode userValue in userList)
{
XmlNodeList userContent = userValue.ChildNodes;
objUser = new Dictionary<string, string>();
foreach(XmlNode value in userContent)
{
objUser.Add (value.Name, value.InnerText);
}
userFullDetails.Add (objUser);
userCountInXml = userList.Count;
userId = new string[userList.Count];
questionSetOfUser = new string[userList.Count];
}
AssignUserXmlValuesToArray ();
}

Related

GameObject.Find not working with string var

I cannot get GameObject.Find to work by passing a string variable as an agrument.
Here is the code:
public IEnumerator GetControls(string uri)
{
using (UnityWebRequest webRequest = UnityWebRequest.Get(uri))
{
yield return webRequest.SendWebRequest();
controls = new JSONObject(webRequest.downloadHandler.text);
GameObject controlGO;
string keyName;
foreach (JSONObject control in controls)
{
keyName = control["keyName"].ToString();
controlGO = GameObject.Find(keyName); //WONT FIND IT
controlGO = GameObject.Find("growLight3"); //WILL FIND IT
}
}
}

Open OSM pbf results in Protobuf exception

Using OSMSharp I am having trouble to open a stream for a file (which I can provide on demand)
The error occurs in PBFReader (line 104)
using (var tmp = new LimitedStream(_stream, length))
{
header = _runtimeTypeModel.Deserialize(tmp, null, _blockHeaderType) as BlobHeader;
}
and states: "ProtoBuf.ProtoException: 'Invalid field in source data: 0'" which might mean different things as I have read in this SO question.
The file opens and is visualized with QGis so is not corrupt in my opinion.
Can it be that the contracts do not match? Is OsmSharp/core updated to the latest .proto files for OSM from here (although not sure if this is the real original source for the definition files).
And what might make more sense, can it be that the file I attached is generated for v2 of OSM PBF specification?
In the code at the line of the exception I see the following comment which makes me wonder:
// TODO: remove some of the v1 specific code.
// TODO: this means also to use the built-in capped streams.
// code borrowed from: http://stackoverflow.com/questions/4663298/protobuf-net-deserialize-open-street-maps
// I'm just being lazy and re-using something "close enough" here
// note that v2 has a big-endian option, but Fixed32 assumes little-endian - we
// actually need the other way around (network byte order):
// length = IntLittleEndianToBigEndian((uint)length);
BlobHeader header;
// again, v2 has capped-streams built in, but I'm deliberately
// limiting myself to v1 features
So this makes me wonder if OSM Sharp is (still) up-to-date.
My sandbox code looks like this:
using OsmSharp.Streams;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using OsmSharp.Tags;
namespace OsmSharp
{
class Program
{
private const string Path = #"C:\Users\Bernoulli IT\Documents\Applications\Argaleo\Test\";
private const string FileNameAntarctica = "antarctica-latest.osm";
private const string FileNameOSPbf = "OSPbf";
private const Boolean useRegisterSource = false;
private static KeyValuePair<string, string> KeyValuePair = new KeyValuePair<string, string>("joep", "monita");
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
//string fileName = $#"{Path}\{FileNameAntarctica}.pbf";
string fileName = $#"{Path}\{FileNameOSPbf}.pbf";
string newFileName = $"{fileName.Replace(".pbf", string.Empty)}-{Guid.NewGuid().ToString().Substring(0, 4)}.pbf";
Console.WriteLine("*** Complete");
string fileNameOutput = CompleteFlow(fileName, newFileName);
Console.WriteLine("");
Console.WriteLine("*** Display");
DisplayFlow(fileNameOutput);
Console.ReadLine();
}
private static string CompleteFlow(string fileName, string newFileName)
{
// 1. Open file and convert to bytes
byte[] fileBytes = FileToBytes(fileName);
// 2. Bytes to OSM stream source (pbf)
PBFOsmStreamSource osmStreamSource;
osmStreamSource = BytesToOsmStreamSource(fileBytes);
osmStreamSource.MoveNext();
if (osmStreamSource.Current() == null)
{
osmStreamSource = FileToOsmStreamSource(fileName);
osmStreamSource.MoveNext();
if (osmStreamSource.Current() == null)
{
throw new Exception("No current in stream.");
}
}
// 3. Add custom tag
AddTag(osmStreamSource);
// 4. OSM stream source to bytes
//byte[] osmStreamSourceBytes = OsmStreamSourceToBytes(osmStreamSource);
// 5. Bytes to file
//string fileNameOutput = BytesToFile(osmStreamSourceBytes, newFileName);
OsmStreamSourceToFile(osmStreamSource, newFileName);
Console.WriteLine(newFileName);
return newFileName;
}
private static void DisplayFlow(string fileName)
{
// 1. Open file and convert to bytes
byte[] fileBytes = FileToBytes(fileName);
// 2. Bytes to OSM stream source (pbf)
BytesToOsmStreamSource(fileBytes);
}
private static byte[] FileToBytes(string fileName)
{
Console.WriteLine(fileName);
return File.ReadAllBytes(fileName);
}
private static PBFOsmStreamSource BytesToOsmStreamSource(byte[] bytes)
{
MemoryStream memoryStream = new MemoryStream(bytes);
memoryStream.Position = 0;
PBFOsmStreamSource osmStreamSource = new PBFOsmStreamSource(memoryStream);
foreach (OsmGeo element in osmStreamSource.Where(osmGeo => osmGeo.Tags.Any(tag => tag.Key.StartsWith(KeyValuePair.Key))))
{
foreach (Tag elementTag in element.Tags.Where(tag => tag.Key.StartsWith(KeyValuePair.Key)))
{
Console.WriteLine("!!!!!!!!!!!!!! Tag found while reading !!!!!!!!!!!!!!!!!!".ToUpper());
}
}
return osmStreamSource;
}
private static PBFOsmStreamSource FileToOsmStreamSource(string fileName)
{
using (FileStream fileStream = new FileInfo(fileName).OpenRead())
{
PBFOsmStreamSource osmStreamSource = new PBFOsmStreamSource(fileStream);
return osmStreamSource;
}
}
private static void AddTag(PBFOsmStreamSource osmStreamSource)
{
osmStreamSource.Reset();
OsmGeo osmGeo = null;
while (osmGeo == null)
{
osmStreamSource.MoveNext();
osmGeo = osmStreamSource.Current();
if(osmGeo?.Tags == null)
{
osmGeo = null;
}
}
osmGeo.Tags.Add("joep", "monita");
Console.WriteLine($"{osmGeo.Tags.FirstOrDefault(tag => tag.Key.StartsWith(KeyValuePair.Key)).Key} - {osmGeo.Tags.FirstOrDefault(tag => tag.Key.StartsWith(KeyValuePair.Key)).Value}");
}
private static byte[] OsmStreamSourceToBytes(PBFOsmStreamSource osmStreamSource)
{
MemoryStream memoryStream = new MemoryStream();
PBFOsmStreamTarget target = new PBFOsmStreamTarget(memoryStream, true);
osmStreamSource.Reset();
target.Initialize();
UpdateTarget(osmStreamSource, target);
target.Flush();
target.Close();
return memoryStream.ToArray();
}
private static string BytesToFile(byte[] bytes, string fileName)
{
using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
{
fs.Write(bytes, 0, bytes.Length);
}
return fileName;
}
private static void OsmStreamSourceToFile(PBFOsmStreamSource osmStreamSource, string fileName)
{
using (FileStream fileStream = new FileInfo(fileName).OpenWrite())
{
PBFOsmStreamTarget target = new PBFOsmStreamTarget(fileStream, true);
osmStreamSource.Reset();
target.Initialize();
UpdateTarget(osmStreamSource, target);
target.Flush();
target.Close();
}
}
private static void UpdateTarget(OsmStreamSource osmStreamSource, OsmStreamTarget osmStreamTarget)
{
if (useRegisterSource)
{
osmStreamTarget.RegisterSource(osmStreamSource, osmGeo => true);
osmStreamTarget.Pull();
}
else
{
bool isFirst = true;
foreach (OsmGeo osmGeo in osmStreamSource)
{
Tag? tag = osmGeo.Tags?.FirstOrDefault(t => t.Key == KeyValuePair.Key);
switch (osmGeo.Type)
{
case OsmGeoType.Node:
if (isFirst)
{
for (int indexer = 0; indexer < 1; indexer++)
{
(osmGeo as Node).Tags.Add(new Tag(KeyValuePair.Key + Guid.NewGuid(), KeyValuePair.Value));
}
isFirst = false;
}
osmStreamTarget.AddNode(osmGeo as Node);
break;
case OsmGeoType.Way:
osmStreamTarget.AddWay(osmGeo as Way);
break;
case OsmGeoType.Relation:
osmStreamTarget.AddRelation(osmGeo as Relation);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
}
}
}
Already I posted this question on the GITHube page of OSMSharp as is linked here. Any help would be very appreciated.

Encountered Invalid redirect. Missing location header. Unity issue

I am using Unity WWWForm to post licence validation request to a URL.
The code is working in Unity 5.6, but it is not working in Unity 2017.3.1f1. I also tried this in Unity 2018. It didn't work.
This is the error message:
Encountered invalid redirect (missing Location header?)
This is the code I am using.
void Awake() {
Instance = this;
WWWForm form = new WWWForm ();
mainHeader = form.headers;
mainHeader ["Authorization"] = "Basic " + System.Convert.ToBase64String (System.Text.Encoding.ASCII.GetBytes ("dummyId:#dummyPassword"));
}
public void HitForLicence(){
string jsonData = JsonUtility.ToJson (new LicenseData {
LICENCE_KEY="kwsnfdksfksnf",
MACHINE_IP="192.168.1.1"
});
Debug.Log (jsonData);
byte[ ] postData = System.Text.Encoding.ASCII.GetBytes (jsonData);
//headers ["Authorization"] = "Basic " + System.Convert.ToBase64String (System.Text.Encoding.ASCII.GetBytes ("unity:#piun!ty"));
if (mainHeader.ContainsKey ("Content-Type")) {
mainHeader ["Content-Type"] = "application/json";
} else {
mainHeader.Add ("Content-Type", "application/json");
}
WWW www = new WWW (LicenseURL, postData, mainHeader);
StartCoroutine (CheckForLicense (www));
}
public IEnumerator CheckForLicense (WWW www)
{
Debug.Log("Check For License..");
yield return www;
//if (www.isDone ) {
if (www.error != null) {
ClearKeyBox ();
print (www.error);
}
else {
print (www.text);
jsonNode = SimpleJSON.JSON.Parse(www.text);
print ("MSG "+ jsonNode["MSG"].ToString());
}
//}
if (jsonNode != null && jsonNode["MSG"].Equals(ValidStr)) {
HandleTextFile.WriteString(_SystemMACAddress+"-"+keyEntered);
// Next screen
} else {
ClearKeyBox ();
}
}
Anyone faced this before? Please help.
I had some problems with WWW under Unity 2018, too.
Currently I am using UnityWebRequest - I think WWW is obsolete, but I can not find any reference to this.
Basically change your code like this:
...
UnityWebRequest www = UnityWebRequest.Post(LicenseURL, form)
StartCoroutine (CheckForLicense (www));
}
public IEnumerator CheckForLicense (WWW www)
{
Debug.Log("Check For License..");
...
I think you have to set the head via SetRequestHeader and put your post data into the WWWForm...
I am not able to check it right now... Hopefully it helps!
Like dome12b said, change to UnityWebRequest.
Additionaly however, set chunked transfer to false. I had the same problem and it was driving me nuts. Chunked transfer fixed it all.
UnityWebRequest www = UnityWebRequest.Post(LicenseURL, form)
www.chunkedTransfer = false;
This finally solved my problem.
public void Post(string url)
{
ServicePointManager.ServerCertificateValidationCallback =
delegate(object s, X509Certificate certificate,
X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
};
string jsonData = JsonUtility.ToJson (new LicenseData {
LICENCE_KEY="kwsnfdksfksnf",
MACHINE_IP="192.168.1.1"
});
Debug.Log (jsonData);
byte[ ] postData = System.Text.Encoding.ASCII.GetBytes (jsonData);
if (mainHeader.ContainsKey ("Content-Type")) {
mainHeader ["Content-Type"] = "application/json";
} else {
mainHeader.Add ("Content-Type", "application/json");
}
StartCoroutine (HttpRequest(postData, url));
}
IEnumerator HttpRequest(byte[] postData, string url)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.AllowAutoRedirect = false;
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string jsonData = JsonUtility.ToJson(new LicenseData
{
LICENCE_KEY = "kwsnfdksfksnf",
MACHINE_IP = "192.168.1.1"
});
streamWriter.Write(jsonData);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
print(result);
}
yield return null;
}

Unity WebGL build with SCORM 1.2 is not working in LMS

I have integrated SCORM 1.2 with my game which produces WebGL output, if we play the WebGL out directly in browser its working fine and not working in LMS. Found that the game play script included in the game causing the issue, when I disable it and upload the build in LMS its loading (can't proceed with game-play, since script is disabled)
In this script I am using GAF function, Xml data fetching from file placed in StreamingAssets folder, not using any WWW class.
SCORM asset pack included in game,
https://www.assetstore.unity3d.com/en/#!/content/53523
Have no idea which function restricting the game from running, could you please have a look on this and send me the feedback.
Error message
Please find the attachment.enter image description here
Access StreamingAssets path folder using WWW class
https://docs.unity3d.com/ScriptReference/Application-streamingAssetsPath.html
public string filePath = Application.streamingAssetsPath + "/UserDetails.xml";
public string result = "";
void Awake ()
{
filePath = Application.streamingAssetsPath + "/UserDetails.xml";
}
void Start ()
{
StartCoroutine(userDetailsXmlPath() );
}
IEnumerator userDetailsXmlPath()
{
print (filePath);
if (filePath.Contains ("://") || filePath.Contains (":///")) {
WWW www = new WWW (filePath);
yield return www;
result = www.text;
print (result);
FetchUserDetails ();
} else {
result = File.ReadAllText (filePath);
print (result);
FetchUserDetails ();
}
}
public void FetchUserDetails()
{
XmlDocument userXml1 = new XmlDocument ();
userXml1.LoadXml(result);
XmlNodeList userList = userXml1.GetElementsByTagName ("user");
foreach(XmlNode userValue in userList)
{
XmlNodeList userContent = userValue.ChildNodes;
objUser = new Dictionary<string, string>();
foreach(XmlNode value in userContent)
{
objUser.Add (value.Name, value.InnerText);
}
userFullDetails.Add (objUser);
userCountInXml = userList.Count;
userId = new string[userList.Count];
questionSetOfUser = new string[userList.Count];
}
AssignUserXmlValuesToArray ();
}

IPP Add Account - The Account Isn't Valid

I am trying to add a bank account to QuickBooks Online using IPP. My code fails and says the account isn't valid. Here is my code:
Account account = new Account();
account.Desc = "Desc";
account.Name = "Checking2";
account.Type = AccountTypeEnum.Revenue;
account.TypeSpecified = true;
account.Subtype = AccountSubtypeEnum.Bank.ToString();
dataServices.Add(account);
Do I need to add fields? I also receive errors that an account with the same name exists, however, I do not see it.
I don't see any XML in my log:
OAuthRequestValidator oauthValidator = new OAuthRequestValidator(accessToken, accessTokenSecret, ConfigurationManager.AppSettings["consumerKey"].ToString(), ConfigurationManager.AppSettings["consumerSecret"].ToString());
ServiceContext context = new ServiceContext(oauthValidator, accessToken, companyID, IntuitServicesType.QBO);
context.EnableServiceRequestsLogging = true;
context.IdsLogger = new MyCustomLogger();
dataServices = new DataServices(context);
return "OK";
public class MyCustomLogger : ILogger
{
public MyCustomLogger()
{
}
public string ClearLog()
{
try
{
string path = HttpContext.Current.Server.MapPath("/qblog.txt");
if (File.Exists(path))
{
File.Delete(path);
}
return "OK";
}
catch (Exception ex)
{
return ex.ToString();
}
}
public void Log(TraceLevel idsTraceLevel, string messageToWrite)
{
string level = idsTraceLevel.ToString();
WriteToLog(new ErrorMessage(MessageSeverity.Error, "QBFS", messageToWrite));
}
public string WriteToLog(ErrorMessage message)
{
if (!String.IsNullOrEmpty(message.Message))
{
string path = HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath + "/qblog.txt");
FileStream fileStream = null;
//If the file exists, then append it
if (File.Exists(path))
{
fileStream = new FileStream(path, FileMode.Append);
}
else
{
fileStream = new FileStream(path, FileMode.OpenOrCreate);
}
StreamWriter sw = new StreamWriter(fileStream);
try
{
sw.WriteLine(String.Format("{0} : {1} {2} {3}", message.ApplicationName, message.Severity, DateTime.Now, message.Message));
return "OK";
}
//If there is an error, just do nothing. Don't stop.
catch (Exception ex)
{
return ex.ToString();
}
finally
{
sw.Close();
fileStream.Close();
}
}
return "Message is null or empty";
}
}
Here is my xml request:
<?xml version="1.0" encoding="utf-8"?><q1:Account xmlns="http://www.intuit.com/sb/cdm/qbo" xmlns:q1="http://www.intuit.com/sb/cdm/v2"><q1:Name>Checking</q1:Name><q1:Desc>Desc</q1:Desc><q1:Subtype>Bank</q1:Subtype></q1:Account>
Here is my response:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><FaultInfo xmlns="http://www.intuit.com/sb/cdm/baseexceptionmodel/xsd"><Message>Another account is already using this name. Please use a different name.</Message><ErrorCode>BAD_REQUEST</ErrorCode><Cause>-11202</Cause></FaultInfo>
I needed to specify the opening and current balance with the true variables:
ac = new Account();
ac.Desc = "Desc";
ac.Name = "Testy";
ac.Subtype = QboAccountDetailTypeEnum.Checking.ToString();
ac.OpeningBalanceDate = DateTime.Now;
ac.OpeningBalanceDateSpecified = true;
ac.CurrentBalance = 0;
ac.CurrentBalanceSpecified = true;
dataServices.Add(ac);
My Subtype was also incorrect. I needed to use the QboAccountDetailTypeEnum.