So I have this application in Unity that I am making and I am trying to connect it to a mySQL database that I made and connected to a website. I am able to insert things through a form on the website into the database. That is working.
What I want to do next is connect the Unity app so that it can also access the things in the database. I am coding in C# and php. I want the unity application to ask the website for certain information from the database. The website should then look in the database and return some info to the unity application.
THIS IS NOT A DUPLICATE question. I have looked at the questions on here and I still can't get it to work. Right now my unity application is able to send a message to my webpage which my webpage then echos properly. (I know this isn't the functionality I talked about but I am just testing right now). However when I then go try to get my response in my Unity application from my webpage, all I debug is <html>.
You can access my website at: http://historicstructures.org/forms.html
Here is my php code:
<html>
<style type="text/css">
body {background-color:#666666; color: white;}
</style>
<body>
<h1 align = "center">
<img src="housebackground.jpg" alt="Mountain View" style="width:97%;height:228px;" ></h1>
<h1 align = "center">Submission Status</h1>
<p align = "center">
<?php
//this is the variable that is being recieved from the unity script
$AuthorName = $_POST["Author"];
//here i am printing it out so that it will be sent back to the unity script
// i am also echoing it onto the webpage so that i know it is getting the variable
//correctly from the unity script
echo $AuthorName;
header("Access-Control-Allow-Origin: *");
print($AuthorName);
//gets all the variables the user inputted to form
$StructureName = $_POST["StructureName"];
$Author = $_POST["Author"];
$YearBuilt = $_POST["YearBuilt"];
$EraBuilt = $_POST["EraBuilt"];
$YearDestroyed = $_POST["YearDestroyed"];
$EraDestroyed = $_POST["EraDestroyed"];
$Latitude = $_POST["Latitude"];
$Longitude = $_POST["Longitude"];
$Structurelink = "no exist yet";
//checks to make sure the information is in the right format
$isValid = true;
$errCode = 0;
if ($Latitude<-90 || $Latitude>90){
$isValid = false;
$errCode = 1;
}
if ($Longitude<-180 || $Longitude>180){
$isValid = false;
$errCode = 2;
}
if ($YearBuilt<-400 || $YearBuilt>400){
$isValid = false;
$errCode = 3;
}
if ($YearDestroyed<-400 || $YearDestroyed>400){
$isValid = false;
$errCode = 4;
}
//if the informationt the user gave was correct, then insert into database
if ($isValid ==true){
$servername = "localhost";
$username = "...";
$password = "...";
$dbname = "StructureInfo";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO info (ID, StructureName, Author, YearBuilt, EraBuilt, YearDestroyed, EraDestroyed, Latitude, Longitude, StructureLink)
VALUES ('null','$StructureName','$Author','$YearBuilt','$EraBuilt','$YearDestroyed','$EraDestroyed','$Latitude','$Longitude','$Structurelink')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
//the user has an error in the information they inputted
else{
echo "Your submission was invalid and so it was not submitted. ";
switch ($errCode) {
case 1:
echo "Your latitude is out of bounds.";
break;
case 2:
echo "Your longitude is out of bounds. ";
break;
case 3:
echo "Your year built is out of bounds. ";
break;
case 4:
echo "Your year destroyed is out of bounds. ";
break;
default:
echo "Go back and review your data to make sure it is correct.";
}
}
?>
</p>
<br><br>
</body>
</html>
Here is my unity code which is attached to a button, I wasn't sure where to put it so my onclick for the button is the main of this js:
#pragma strict
function Start () {
}
function Update () {
}
function GetFromDB(){
var url = "http://historicstructures.org/action_page_post.php";
var form = new WWWForm();
form.AddField( "Author", "Jess" );
var www = new WWW( url, form );
// wait for request to complete
yield www;
// and check for errors
if (www.error == null)
{
Debug.Log(www.text);
} else {
// something wrong!
Debug.Log("WWW Error: "+ www.error);
}
}
GetFromDB();
First of all, your code is Javascript/Unityscript but you tagged C#. I think that you should be using C# as it has more features and support than Javascript/Unityscript.
Here is my unity code which is attached to a button, I wasn't sure
where to put it so my onclick for the button is the main of this js
Create a C# script then subscribe to the Button's onClick event. When the Button is pressed, Start coroutine that will connect to your database.
public Button button;
void OnEnable()
{
button.onClick.AddListener(() => { StartCoroutine(GetFromDB()); });
}
void OnDisable()
{
button.onClick.RemoveAllListeners();
}
IEnumerator GetFromDB()
{
var url = "http://historicstructures.org/action_page_post.php";
var form = new WWWForm();
form.AddField("Author", "Jess");
WWW www = new WWW(url, form);
// wait for request to complete
yield return www;
// and check for errors
if (String.IsNullOrEmpty(www.error))
{
UnityEngine.Debug.Log(www.text);
}
else
{
// something wrong!
UnityEngine.Debug.Log("WWW Error: " + www.error);
}
}
If you are new to C#, this Unity tutorial should get you started. You can find other Unity UI event samples here.
EDIT:
However when I then go try to get my response in my Unity application
from my webpage, all I debug is <html>.
I didn't see the <html> in your original question. That's because <html> can be used on stackoverflow to arrange text. I edited your question and formatted the <html> into a code to make it show up.
There is nothing wrong with your code. Unity simply did not display all other data received from the server because there is a new line in your code. Simply click on the <html> log you see in the Editor and it show you all the other data from the server. You must click on that error in the Editor to see the rest of the data.
Note that your current script will output error to Unity:
Your submission was invalid and so it was not submitted.
That's because you did not fill all the forms required.
This should do it:
form.AddField("Author", "Jess");
form.AddField("YearDestroyed", "300");
form.AddField("YearBuilt", "300");
form.AddField("Longitude", "170");
form.AddField("Latitude", "60");
form.AddField("StructureName", "IDK");
Few more things:
1.Remove the html code from your server. That should not be there if you want to use POST/GET. It will be hard to extract your data if you have the html code there. So, your code should only start from <?php and end with ?>
2.If you are going to receive more than 1 data from the server, use json.
On the PHP side, use json_encode to convert your data to json the send to Unity with print or echo. Google json_encode for more information.
On Unity C# side, use JsonUtility or JsonHelper from this post to deserialize the data from the server.
3.Finally, instead of building the error message and outputting to Unity from the server, simply send the error code from the server.
On Unity C# side, make a class that converts the error code into full error message.
Related
How can I get InlineKeyboardCallbackButton clicked in telegram bot?
Here is my code : I Edited The Code
public async System.Threading.Tasks.Task<ActionResult> GetMsgAsync()
{
var req = Request.InputStream;
var responsString = new StreamReader(req).ReadToEnd();
var update = JsonConvert.DeserializeObject<Update>(responsString);
var message = update.Message;
var chat = message.Chat;
InlineKeyboardMarkup categoryInlineMarkup = new
InlineKeyboardMarkup(
new InlineKeyboardButton[][]
{
new InlineKeyboardButton[]
{
new InlineKeyboardCallbackButton("button1","callbackData")
}
}
);
await api.SendTextMessageAsync(update.Message.Chat.Id, "Please click the button", replyMarkup: categoryInlineMarkup);
if (update.Type == Telegram.Bot.Types.Enums.UpdateType.MessageUpdate)
{
// all codes just run in this block
}
if (update.Type == Telegram.Bot.Types.Enums.UpdateType.CallbackQueryUpdate)
{
// I can't get clicked button here
if (update.CallbackQuery.Data.Contains("callbackData"))
{
await api.AnswerCallbackQueryAsync(update.CallbackQuery.Id, update.CallbackQuery.Data);
}
}
}
How can I get this button clicked also in webhook method, not in console program?
Finally i find out the answer, the problem is this line of code :
var message = update.Message;
this line of code is the main problem because this line is not in try
catch block and i can't understand which line is the problem .
After this Problem, i have a suggestion for you
You can debugging your telegram bot in your personal computer without uploading any code on any host, for this purpose You can run 3 below steps ::
1- Accessing an IIS Express site from a remote computer
2- Download NGROK
3- after download ngrok you can forward telegram webhook requests to your personal computer .
I got this php on my server, that is called to run when I click on a button to add currency:
// Select player_name
$check = mysqli_query($conn,"select Currency from player where Name='$player_name'");
$checkrows=mysqli_num_rows($check);
if($checkrows==1) {
$sql = "INSERT INTO player (Currency) VALUES ('post_player_currency')";
$result = mysqli_query($conn, $sql) or die('Error querying database.');
echo ("DATABASE: Currency added ");
} else {
// Insert player into database
echo "DATABASE: Currency NOT added ";
}
?>
And on my Unity C# script, I have this:
public IEnumerator AddCurrency(Text playername, Text playercurrency) {
_tempCoins = int.Parse(coins.text);
_tempCoins += 10;
coins.text = _tempCoins.ToString();
WWWForm form = new WWWForm ();
form.AddField ("post_player_name", playername.text);
form.AddField ("post_player_currency", playercurrency.text);
WWW www = new WWW (RegisterPlayerURL, form);
yield return www;
print (www.text);
if (www.text == "DATABASE: Currency added ") {
print ("TRANSACTION: Current Coins: " + _tempCoins);
}
}
The scripts themselves are working, but what I don't understand is why I get Error querying database. everytime as result, instead of it actually adding the value to the database.
A very similar script to register a player to the database that I made, is working just fine. I've spent a lot of time and I cannot figure out why this one doesn't work.
Help is appreciated! Thanks!
So I have a script in unity that connects to a MySQL database through a PHP script. The PHP script is working fine, but I can't connect to the PHP file from Unity (C# script). The URL for the WWW is localhost and that is for XAMPP (don't know if that is the problem)
Here is my code:
private string CreateAccountUrl = "http://localhost/CreateAccountScript.php";
IEnumerator CreateAccount()
{
WWWForm Form = new WWWForm();
Form.AddField("Email", CEmail);
Form.AddField("Password", CPassword);
Form.AddField("Username", CUsername);
WWW CreateAccountWWW = new WWW(CreateAccountUrl, Form);
yield return CreateAccountWWW;
if (CreateAccountWWW.error != "Null")
{
Debug.LogError("Cannot Connect to Account Creation!");
}else
{
string CreateAccountReturn = CreateAccountWWW.text;
if (CreateAccountReturn == "Success")
{
Debug.Log(CreateAccountReturn);
CreateAccountMenuHolder.SetActive(false);
ConfirmEmailMenuHolder.SetActive(true);
}else if (CreateAccountReturn == "DB Error")
{
Debug.LogError("DB ERROR!");
}else if (CreateAccountReturn == "Can't connect to DB (connect)")
{
Debug.LogError("Can't connect to DB (connect)");
}else if (CreateAccountReturn == "Can't connect to DB (select)")
{
Debug.LogError("Can't connect to DB (select)");
}
}
}
Please ignore the error debugs, they were only for testing...
If you need my PHP code please say it, because I really need the help.
Thanks in advance!
There probably is no error, but with your current code you'll always think there is one. You have the following error comparison:
if (CreateAccountWWW.error != "Null")
{
Debug.LogError("Cannot Connect to Account Creation!");
}
That is, you're comparing the possible error message against the string "Null". That is not what you want to do. You want to check if your error member is actually null. That is
if (CreateAccountWWW.error != null)
Or, alternatively
if(!string.IsNullOrEmpty(CreateAccountWWW.error))
That should do the trick.
My goal is to make a open source YouTube player that can be controlled via global media keys.
The global key issue I got it covered but the communication between the YouTube player and my Windows Forms application just doesn't work for some reason.
So far this is what I have:
private AxShockwaveFlashObjects.AxShockwaveFlash player;
player.movie = "http://youtube.googleapis.com/v/9bZkp7q19f0"
...
private void playBtn_Click(object sender, EventArgs e)
{
player.CallFunction("<invoke name=\"playVideo\" returntype=\"xml\"></invoke>");
}
Unfortunately this returns:
"Error HRESULT E_FAIL has been returned from a call to a COM component."
What am I missing? Should I load a different URL?
The documentation states that YouTube player uses ExternalInterface class to control it from JavaScript or AS3 so it should work with c#.
UPDATED:
Method used to embed the player: http://www.youtube.com/watch?v=kg-z8JfOIKw
Also tried to use the JavaScript-API in the WebBrowser control but no luck (player just didn't respond to JavaScript commands, tried even to set WebBrowser.url to a working demo, all that I succeeded is to get the onYouTubePlayerReady() to fire using the simple embedded object version )
I think there might be some security issues that I'm overseeing, don't know.
UPDATE 2:
fond solution, see my answer below.
It sounds like your trying to use Adobe Flash as your interface; then pass certain variables back into C#.
An example would be this:
In Flash; create a button... Actionscript:
on (press) {
fscommand("Yo","dude");
}
Then Visual Studio you just need to add the COM object reference: Shockwave Flash Object
Then set the embed to true;
Then inside Visual Studio you should be able to go to Properties; find fscommand. The fscommand will allow you to physically connect the value from the Flash movie.
AxShockwaveFlashObjects._IShockwaveFlashEvents_FSCommandEvent
That collects; then just use e.command and e.arg for example to have the collected item do something.
Then add this to the EventHandler;
lbl_Result.Text="The "+e.args.ToString()+" "+e.command.ToString()+" was clicked";
And boom it's transmitting it's data from Flash into Visual Studio. No need for any crazy difficult sockets.
On a side note; if you have Flash inside Visual Studio the key is to ensure it's "embed is set to true." That will hold all the path references within the Flash Object; to avoid any miscalling to incorrect paths.
I'm not sure if that is the answer your seeking; or answers your question. But without more details on your goal / error. I can't assist you.
Hope this helps. The first portion should actually show you the best way to embed your Shockwave into Visual Studio.
Make sure you add the correct reference:
Inside your project open 'Solution Explorer'
Right-Click to 'Add Reference'
Go to 'COM Object'
Find Proper object;
COM Objects:
Shockwave ActiveX
Flash Accessibility
Flash Broker
Shockwave Flash
Hope that helps.
It sounds like you aren't embedding it correctly; so you can make the call to it. If I'm slightly mistaken; or is this what you meant:
If your having difficulty Ryk had a post awhile back; with a method to embed YouTube videos:
<% MyYoutubeUtils.ShowEmebddedVideo("<object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/gtNlQodFMi8&hl=en&fs=1"></param><param name="allowFullScreen" value="true"></param><embed src="http://www.youtube.com/v/gtNlQodFMi8&hl=en&fs=1" type="application/x-shockwave-flash" allowfullscreen="true" width="425" height="344"></embed></object>") %>
Or...
public static string ShowEmbeddedVideo(string youtubeObject)
{
var xdoc = XDocument.Parse(youtubeObject);
var returnObject = string.Format("<object type=\"{0}\" data=\{1}\"><param name=\"movie\" value=\"{1}\" />",
xdoc.Root.Element("embed").Attribute("type").Value,
xdoc.Root.Element("embed").Attribute("src").Value);
return returnObject;
}
Which you can find the thread here: https://stackoverflow.com/questions/2547101/purify-embedding-youtube-videos-method-in-c-sharp
I do apologize if my post appears fragmented; but I couldn't tell if it was the reference, the variable, the method, or embed that was causing you difficulties. Truly hope this helps; or give me more details and I'll tweak my response accordingly.
C# to ActionScript Communication:
import flash.external.ExternalInterface;
ExternalInterface.addCallback("loadAndPlayVideo", null, loadAndPlayVideo);
function loadAndPlayVideo(uri:String):void
{
videoPlayer.contentPath = uri;
}
Then in C#; add an instance of the ActiveX control and add the content into a Constructor.
private AxShockwaveFlash flashPlayer;
public FLVPlayer ()
{
// Add Error Handling; to condense I left out.
flashPlayer.LoadMovie(0, Application.StartupPath + "\\player.swf");
}
fileDialog = new OpenFileDialog();
fileDialog.Filter = "*.flv|*.flv";
fileDialog.Title = "Select a Flash Video File...";
fileDialog.Multiselect = false;
fileDialog.RestoreDirectory = true;
if (fileDialog.ShowDialog() == DialogResult.OK)
{
flashPlayer.CallFunction("<invoke" + " name=\"loadAndPlayVideo\" returntype=\"xml"> <arguements><string>" + fileDialog.FileName + "</string></arguements></invoke>");
}
ActionScript Communication to C#:
import flash.external.ExternalInterface;
ExternalInterface.call("ResizePlayer", videoPlayer.metadata.width, videoPlayer.metadata.height);
flashPlayer.FlashCall += new _IShockwaveFlashEvents_FlashCallEventHandler(flashPlayer_FlashCall);
Then the XML should appear:
<invoke name="ResizePlayer" returntype="xml">
<arguements>
<number> 320 </number>
<number> 240 </number>
</arguments>
</invoke>
Then parse the XML in the event handler and invoke the C# function locally.
XmlDocument document = new XmlDocument();
document.LoadXML(e.request);
XmlNodeList list = document.GetElementsByTagName("arguements");
ResizePlayer(Convert.ToInt32(list[0].FirstChild.InnerText), Convert.ToInt32(list[0].ChildNodes[1].InnerText));
Now they are both passing data back and forth. That is a basic example; but by utilizing the ActionScript Communication you shouldn't have any issues utilizing the native API.
Hope that is more helpful. You can expand on that idea by a utility class for reuse. Obviously the above code has some limitations; but hopefully it points you in the right direction. Was that direction you were attempting to go? Or did I still miss the point?
Create a new Flash Movie; in ActionScript 3. Then on the initial first frame; apply the below:
Security.allowDomain("www.youtube.com");
var my_player:Object;
var my_loader:Loader = new Loader();
my_loader.load(new URLRequest("http://www.youtube.com/apiplayer?version=3"))
my_loader.contentLoaderInfo.addEventListener(Event.INIT, onLoaderInit);
function onLoaderInit(e:Event):void{
addChild(my_loader);
my_player = my_loader.content;
my_player.addEventListener("onReady", onPlayerReady);
}
function onPlayerReady(e:Event):void{
my_player.setSize(640,360);
my_player.loadVideoById("_OBlgSz8sSM",0);
}
So what exactly is that script doing? It is utilizing the native API and using ActionScript Communication. So below I'll break down each line.
Security.allowDomain("www.youtube.com");
Without that line YouTube won't interact with the object.
var my_player:Object;
You can't just load a movie into the movie; so we will create a variable Object. You have to load a special .swf that will contain access to those codes. The below; does just that. So you can access the API.
var my_loader:Loader = new Loader();
my_loader.load(new URLRequest("http://www.youtube.com/apiplayer?version=3"));
We now reference the Google API per their documentation.
my_loader.contentLoaderInfo.addEventListener(Event.INIT, onLoaderInit);
But in order to actually work with our object; we need to wait for it to be fully initialized. So the Event Listener will wait; so we know when we can pass commands to it.
The onLoaderInit function will be triggered upon initialization. Then it's first task will be my_loader to display the list so that the video appears.
The addChild(my_loader); is what will load one; the my_player = my_loader.content; will store a reference for easy access to the object.
Though it has been initialized; you have to wait even further... You use my_player.addEventListener("onReady", onPlayerReady); to wait and listen for those custom events. Which will allow a later function to handle.
Now the player is ready for basic configuration;
function onPlayerReady(e:Event):void{
my_player.setSize(640,360);
}
The above function starts very basic manipulation. Then the last line my_player.loadVideoById("_OBlgSz8sSM",0); is referencing the particular video.
Then on your stage; you could create two buttons and apply:
play_btn.addEventListener(MouseEvent.CLICK, playVid);
function playVid(e:MouseEvent):void {
my_player.playVideo();
}
pause_btn.addEventListener(MouseEvent.CLICK, pauseVid);
function pauseVid(e:MouseEvent):void {
my_player.pauseVideo();
}
Which would give you a play and pause functionality. Some additional items you could use our:
loadVideoById()
cueVideoById()
playVideo()
pauseVideo()
stopVideo()
mute()
unMute()
Keep in mind those can't be used or called until it has been fully initialized. But using that; with the earlier method should allow you to layout the goal and actually pass variables between the two for manipulation.
Hopefully that helps.
I'd start by making sure that javascript can talk to your flash app.
make sure you have: allowScriptAccess="sameDomain" set in the embed (from http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/external/ExternalInterface.html#includeExamplesSummary).
you should validate that html->flash works; then C->html; and gradually work up to C->you-tube-component. you have a lot of potential points of failure between C and the you-tube-component right now and it's hard to address all of them at the same time.
After a lot of tries and head-hammering, I've found a solution:
Seems that the Error HRESULT E_FAIL... happens when the flash dosen't understand the requested flash call. Also for the youtube external api to work, the js api needs to be enabled:
player.movie = "http://www.youtube.com/v/VIDEO_ID?version=3&enablejsapi=1"
As I said in the question the whole program is open source, so you will find the full code at bitbucket. Any advice, suggestions or collaborators are highly appreciated.
The complete solution:
Here is the complete guide for embedding and interacting with the YouTube player or any other flash object.
After following the video tutorial
, set the flash player's FlashCall event to the function that will handle the flash->c# interaction (in my example it's YTplayer_FlashCall )
the generated `InitializeComponent()` should be:
...
this.YTplayer = new AxShockwaveFlashObjects.AxShockwaveFlash();
this.YTplayer.Name = "YTplayer";
this.YTplayer.Enabled = true;
this.YTplayer.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("YTplayer.OcxState")));
this.YTplayer.FlashCall += new AxShockwaveFlashObjects._IShockwaveFlashEvents_FlashCallEventHandler(this.YTplayer_FlashCall);
...
the FlashCall event handler
private void YTplayer_FlashCall(object sender, AxShockwaveFlashObjects._IShockwaveFlashEvents_FlashCallEvent e)
{
Console.Write("YTplayer_FlashCall: raw: "+e.request.ToString()+"\r\n");
// message is in xml format so we need to parse it
XmlDocument document = new XmlDocument();
document.LoadXml(e.request);
// get attributes to see which command flash is trying to call
XmlAttributeCollection attributes = document.FirstChild.Attributes;
String command = attributes.Item(0).InnerText;
// get parameters
XmlNodeList list = document.GetElementsByTagName("arguments");
List<string> listS = new List<string>();
foreach (XmlNode l in list){
listS.Add(l.InnerText);
}
Console.Write("YTplayer_FlashCall: \"" + command.ToString() + "(" + string.Join(",", listS) + ")\r\n");
// Interpret command
switch (command)
{
case "onYouTubePlayerReady": YTready(listS[0]); break;
case "YTStateChange": YTStateChange(listS[0]); break;
case "YTError": YTStateError(listS[0]); break;
default: Console.Write("YTplayer_FlashCall: (unknownCommand)\r\n"); break;
}
}
this will resolve the flash->c# communication
calling the flash external functions (c#->flash):
private string YTplayer_CallFlash(string ytFunction){
string flashXMLrequest = "";
string response="";
string flashFunction="";
List<string> flashFunctionArgs = new List<string>();
Regex func2xml = new Regex(#"([a-z][a-z0-9]*)(\(([^)]*)\))?", RegexOptions.Compiled | RegexOptions.IgnoreCase);
Match fmatch = func2xml.Match(ytFunction);
if(fmatch.Captures.Count != 1){
Console.Write("bad function request string");
return "";
}
flashFunction=fmatch.Groups[1].Value.ToString();
flashXMLrequest = "<invoke name=\"" + flashFunction + "\" returntype=\"xml\">";
if (fmatch.Groups[3].Value.Length > 0)
{
flashFunctionArgs = pars*emphasized text*eDelimitedString(fmatch.Groups[3].Value);
if (flashFunctionArgs.Count > 0)
{
flashXMLrequest += "<arguments><string>";
flashXMLrequest += string.Join("</string><string>", flashFunctionArgs);
flashXMLrequest += "</string></arguments>";
}
}
flashXMLrequest += "</invoke>";
try
{
Console.Write("YTplayer_CallFlash: \"" + flashXMLrequest + "\"\r\n");
response = YTplayer.CallFunction(flashXMLrequest);
Console.Write("YTplayer_CallFlash_response: \"" + response + "\"\r\n");
}
catch
{
Console.Write("YTplayer_CallFlash: error \"" + flashXMLrequest + "\"\r\n");
}
return response;
}
private static List<string> parseDelimitedString (string arguments, char delim = ',')
{
bool inQuotes = false;
bool inNonQuotes = false;
int whiteSpaceCount = 0;
List<string> strings = new List<string>();
StringBuilder sb = new StringBuilder();
foreach (char c in arguments)
{
if (c == '\'' || c == '"')
{
if (!inQuotes)
inQuotes = true;
else
inQuotes = false;
whiteSpaceCount = 0;
}else if (c == delim)
{
if (!inQuotes)
{
if (whiteSpaceCount > 0 && inQuotes)
{
sb.Remove(sb.Length - whiteSpaceCount, whiteSpaceCount);
inNonQuotes = false;
}
strings.Add(sb.Replace("'", string.Empty).Replace("\"", string.Empty).ToString());
sb.Remove(0, sb.Length);
}
else
{
sb.Append(c);
}
whiteSpaceCount = 0;
}
else if (char.IsWhiteSpace(c))
{
if (inNonQuotes || inQuotes)
{
sb.Append(c);
whiteSpaceCount++;
}
}
else
{
if (!inQuotes) inNonQuotes = true;
sb.Append(c);
whiteSpaceCount = 0;
}
}
strings.Add(sb.Replace("'", string.Empty).Replace("\"", string.Empty).ToString());
return strings;
}
adding Youtube event handlers:
private void YTready(string playerID)
{
YTState = true;
//start eventHandlers
YTplayer_CallFlash("addEventListener(\"onStateChange\",\"YTStateChange\")");
YTplayer_CallFlash("addEventListener(\"onError\",\"YTError\")");
}
private void YTStateChange(string YTplayState)
{
switch (int.Parse(YTplayState))
{
case -1: playState = false; break; //not started yet
case 1: playState = true; break; //playing
case 2: playState = false; break; //paused
//case 3: ; break; //buffering
case 0: playState = false; if (!loopFile) mediaNext(); else YTplayer_CallFlash("seekTo(0)"); break; //ended
}
}
private void YTStateError(string error)
{
Console.Write("YTplayer_error: "+error+"\r\n");
}
usage ex:
YTplayer_CallFlash("playVideo()");
YTplayer_CallFlash("pauseVideo()");
YTplayer_CallFlash("loadVideoById(KuNQgln6TL0)");
string currentVideoId = YTplayer_CallFlash("getPlaylist()");
string currentDuration = YTplayer_CallFlash("getDuration()");
The functions YTplayer_CallFlash, YTplayer_FlashCall should work for any flash-C# communication with minor adjustments like the YTplayer_CallFlash's switch (command).
This stumped me for a number of hours.
Just add enable JS to your URL:
http://www.youtube.com/v/9bZkp7q19f0?version=3&enablejsapi=1
CallFunction works fine for me now! Also remove unrequired space in the call.
I am desperately in need of debugging help, been stuck at this error for 6 days now.....
the error I get in my ASp.net app is :
Microsoft JScript runtime error: Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Write(), response filters, HttpModules, or server trace is enabled.
Details: Error parsing near '<script type='text/j'.
Below is the relevant code snippet,
CollyDataExchangeWebService Col_ValSub = new CollyDataExchangeWebService();
CollyReportServiceRequest ServiceReq = new CollyReportServiceRequest();
CollyReportServiceRequestData ServiceReqData = new CollyReportServiceRequestData();
ServiceReqData.AmendmentIndicatorSpecified = true;
ServiceReqData.AmendmentIndicator = false;
ServiceReqData.CollyReport = ColRep;
ServiceReq.ServiceRequestData = ServiceReqData;
ServiceReq.ServiceRequestHeader = ServiceHeader;
errValidate = null;
//btnOK.OnClientClick = "MSGShow()";
bool Valid = true;
string ErrMsgs = "";
if (((System.Web.UI.WebControls.Button)(sender)).CommandArgument == "Validate")
{
CollyReportServiceResponse ValResponse = Col_ValSub.validateReport(ServiceReq);
switch (ValResponse.ServiceResponseHeader.ServiceStatus)
{
case ServiceStatus.Successful:
btnOK.OnClientClick = "";
valHeader.Text = "Validation is Completed. No errors were found";
mlValPopup.Show();
break;
case ServiceStatus.ValidationErrors:
Valid = false;
ErrMsgs = ErrMsgs + _ValidationError(ValResponse);
ValBTN.Update();
mlValPopup.Show();
break;
case ServiceStatus.SystemError:
btnOK.OnClientClick = "";
Valid = false;
ErrMsgs = ErrMsgs + _SystemError(ValResponse);
ValBTN.Update();
mlValPopup.Show();
break;
}
After hours of debugging I found this line to be causing the error:
CollyReportServiceResponse ValResponse = Col_ValSub.validateReport(ServiceReq);
After 6 days of debugging and frustration I found that SOME records cause this issue and others dont in OLDER versions of the code but in new version ALL of the records lead to this error so it has to do something with the data in the DB which means SOME method in the code behaves differently to nulls but I cant find out exactly what the issue is because my app is 30k lines of code
after searching around and trying various solutions, the below 2 are not the solutions to my issue.
forums.asp.net/t/1357862.aspx
http://www.vbforums.com/showthread.php?t=656246
I want to mention that I am already having a difficult time dealing with this application because it was written by other programmers that are now long gone leaving behind non-documented or commented spaghetti code.
I did not code this but other programmers from past have put Response.Write in code:
private void MessageBox(string msg)
{
if (!string.IsNullOrEmpty(msg))
{
Global.tmpmsg = msg;
msg = null;
}
Response.Write("<script type=\"text/javascript\" language=\"javascript\">");
Response.Write("window.open('ErrorPage.aspx?msg=" + "','PopUp','screenX=0,screenY=0,width=700,height=340,resizable=1,status=no,scrollbars=yes,toolbars=no');");
Response.Write("</script>");
}
This one is in another method:
Response.Write("<script type=\"text/javascript\" language=\"javascript\">");
Response.Write("alert('No search resuls were found');");
Response.Write("</script>");
Or This:
if (!string.IsNullOrEmpty(msg))
{
Global.tmpmsg = msg;
Response.Write("<script type=\"text/javascript\" language=\"javascript\">");
Response.Write("window.open('ErrorPage.aspx?msg=" + "','PopUp','screenX=0,screenY=0,width=700,height=340,resizable=1,status=no,scrollbars=yes,toolbars=no');");
Response.Write("</script>");
}
After Jrummel`s comment I added this to code and then nothing at all happened.
private void MessageBox(string msg)
{/*
if (!string.IsNullOrEmpty(msg))
{
Global.tmpmsg = msg;
msg = null;
}
Response.Write("<script type=\"text/javascript\" language=\"javascript\">");
Response.Write("window.open('ErrorPage.aspx?msg=" + "','PopUp','screenX=0,screenY=0,width=700,height=340,resizable=1,status=no,scrollbars=yes,toolbars=no');");
Response.Write("</script>");
*/
// Define the name and type of the client scripts on the page.
String csname1 = "PopupScript";
Type cstype = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the startup script is already registered.
if (!cs.IsStartupScriptRegistered(cstype, csname1))
{
String cstext1 = "<script type=\"text/javascript\" language=\"javascript\">" + " " + "window.open('ErrorPage.aspx?msg=" + "','PopUp','screenX=0,screenY=0,width=700,height=340,resizable=1,status=no,scrollbars=yes,toolbars=no');" + " " + "</script>";
cs.RegisterStartupScript(cstype, csname1, cstext1, false);
}
}
I have found the error after 2 weeks of debugging and 2 days of Brute Forcing:
In one of the 800 DB columns that I have there was a null/improper value. This value reacted with one of the 150 methods in my ASP.NET code in such a way as to present a JavaScript error even though Response.Write() was NOT the issue. I have not found which method it was that reacted to this value but I have found the solution which is to simply input a valid value on the column record..
How a programmer can brute force to find the issue:
In my case after long days of debugging I took a sample of one working record and another sample of an error leading record. Once I had achieved this, I used
DELETE FROM tablename WHERE UniqueColID= unique identifier for the error causing record
Then I did:
INSERT INTO tablename ([uniqueIdentifier],[ column 2],[column 3]) SELECT #UniqueIdentifierofErrorCausingRecord, column2, [column3] FROM TableName WHERE [uniqueIdentifier]=#UniqueIdentifierForWorkingRecord;
What the first statement does is delete the non working record then the 2nd statement reinserts that record with identical column values of the working record but with the UniqueIdentifier of the Non working record. This way I can go through each table to find which table is causing the error and then I can pinpoint which column of that table is the issue.
The specific issue in my case was DateTime.TryParse() because a table column value was inserted in improper format.. The code performed field population in one of the methods without a try and catch using the DateTime.Parse method.... After some testing it seems even a try/catch is not able to pick this error up as it is a javascript error..
Don't use Response.Write().
Instead, create a LiteralControl and add it to the page.
Use ClientScriptManager to add scripts to the page. Here's an example from MSDN:
// Define the name and type of the client scripts on the page.
String csname1 = "PopupScript";
Type cstype = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the startup script is already registered.
if (!cs.IsStartupScriptRegistered(cstype, csname1))
{
String cstext1 = "alert('Hello World');";
cs.RegisterStartupScript(cstype, csname1, cstext1, true);
}