private void btnCreateEmployeeFile_Click(object sender, RoutedEventArgs e)
        {
            List <Employee> employees = JSonReader.ReadJSON("http://dummy.restapiexample.com/api/v1/employees");

            StringBuilder fileContent = new StringBuilder();

            foreach (Employee employee in employees)
            {
                fileContent.Append(employee.ID + "|" + employee.Employee_name + "|" + employee.Employee_salary + "|" + employee.Employee_age + ";");
            }

            SaveFileDialog saveFileDialog = new SaveFileDialog();
            string         folder         = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            saveFileDialog.FileName = "employees.txt";
            saveFileDialog.Filter   = "Tekstbestand (*.txt)|*.txt|C# bestand (*.cs)|*.cs";
            if (saveFileDialog.ShowDialog() == true)
            {
                folder = System.IO.Path.GetDirectoryName(saveFileDialog.FileName);
                string fileName = System.IO.Path.GetFileName(saveFileDialog.FileName);
                try
                {
                    FileWriter.WriteStringToFile(fileContent.ToString(), folder, fileName);

                    lstEmployees.ItemsSource = employees;
                }
                catch (Exception fout)
                {
                    MessageBox.Show(fout.Message, "ERROR");
                }
            }
        }
        /// <summary>
        /// Init constructor.
        /// </summary>
        public BayeuxConnection(IHttpDataSource connection, IHttpDataSource longPollingConnection)
        {
            if (connection == null)
            {
                throw new ArgumentNullException("connection");
            }

            _syncObject  = new object();
            _writerCache = new StringBuilder();
            _jsonWriter  = new JSonWriter(_writerCache, false);
            _jsonWriter.CompactEnumerables = true;
            _jsonReader               = new JSonReader();
            _state                    = BayeuxConnectionState.Disconnected;
            _subscribedChannels       = new List <string>();
            LongPollingRetryDelay     = DefaultRetryDelay;
            LongPollingConnectRetries = DefaultNumberOfConnectRetries;

            _httpConnection = connection;
            _httpConnection.DataReceived      += DataSource_OnDataReceived;
            _httpConnection.DataReceiveFailed += DataSource_OnDataReceiveFailed;

            if (longPollingConnection != null)
            {
                _httpLongPollingConnection = longPollingConnection;
                _httpLongPollingConnection.DataReceived      += LongPollingDataSource_OnDataReceived;
                _httpLongPollingConnection.DataReceiveFailed += LongPollingDataSource_OnDataReceiveFailed;
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Requests the live feed settings values for the application
        /// </summary>
        public async Task <IJSonObject> GetLiveSettings()
        {
            try
            {
                var reader = new JSonReader();

                var response = await _client.GetAsync(new Uri(ServerBaseUri, "/settings"));

                var cr = CheckResponse(response);
                if (cr != null)
                {
                    var creply = reader.ReadAsJSonObject(cr);
                    return(creply);
                }

                var r = await response.Content.ReadAsStringAsync();

                var reply = reader.ReadAsJSonObject(r);
                return(reply);
            }
            catch (Exception)
            {
                return(null);
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Reports a RayzReply
        /// </summary>
        /// <param name="rayzReplyId"> RayzReply ID </param>
        public async Task <IJSonObject> ReportRayzReply(String rayzReplyId)
        {
            try
            {
                var writer = new JSonWriter(true);
                var reader = new JSonReader();

                writer.WriteObjectBegin();
                writer.WriteMember("userId", _deviceId);
                writer.WriteMember("rayzReplyId", rayzReplyId);
                writer.WriteObjectEnd();

                var json = new StringContent(writer.ToString());
                json.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

                var response = await _client.PostAsync(new Uri(ServerBaseUri, "/rayz/reply/report"), json);

                var cr = CheckResponse(response);
                if (cr != null)
                {
                    var creply = reader.ReadAsJSonObject(cr);
                    return(creply);
                }

                var r = await response.Content.ReadAsStringAsync();

                var reply = reader.ReadAsJSonObject(r);
                return(reply);
            }
            catch (Exception)
            {
                return(null);
            }
        }
        private void LoadJsonData()
        {
            var jsonReader = new JSonReader();

            _jsonAccountData = jsonReader.ReadAsJSonObject(File.ReadAllText(@"Resources\accounts.json"));
            _jsonBalanceData = jsonReader.ReadAsJSonObject(File.ReadAllText(@"Resources\accountbalances.json"));
        }
Esempio n. 6
0
        /// <summary>
        /// Requests the latest live feed of the user and a random Rayz from the list
        /// Random is latest
        /// </summary>
        public async Task <IJSonObject> GetLiveFeedRandom()
        {
            try
            {
                var reader = new JSonReader();

                var response = await _client.GetAsync(new Uri(ServerBaseUri, "/user/" + _deviceId + "/livefeed/random"));

                var cr = CheckResponse(response);
                if (cr != null)
                {
                    var creply = reader.ReadAsJSonObject(cr);
                    return(creply);
                }

                var r = await response.Content.ReadAsStringAsync();

                var reply = reader.ReadAsJSonObject(r);
                return(reply);
            }
            catch (Exception)
            {
                return(null);
            }
        }
Esempio n. 7
0
        public void TestMissingMember()
        {
            var reader = new JSonReader("{ \"Name\": \"Jan\" }");
            var result = reader.ReadAsJSonObject().ToObjectValue <SampleAttributedClass>();

            Assert.IsNotNull(result);
        }
Esempio n. 8
0
        public void Write(IJSonWriter output)
        {
            var reader = new JSonReader();
            var tree   = reader.Read(obj.ToString());

            output.Write(tree);
        }
        /// <summary>
        /// Loads recorded set of bayeux messages from an input stream-reader.
        /// </summary>
        public int LoadRecording(TextReader input)
        {
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }

            int addedResponses = 0;

            var reader = new JSonReader(input, true);

            // if not yet end-of-the-input:
            while (input.Peek() != -1)
            {
                try
                {
                    var jObject = reader.ReadAsJSonMutableObject();

                    if (jObject != null)
                    {
                        RecordBayeux("F-" + addedResponses, jObject);
                        addedResponses++;
                    }
                }
                catch (Exception ex)
                {
                    DebugLog.WriteCoreLine("Invalid format of recorded bayeux responses");
                    DebugLog.WriteBayeuxException(ex);
                    break;
                }
            }

            return(addedResponses);
        }
        /// <summary>
        /// Records a response as bayeux message, while only 'data' part of the message is given.
        /// It will try to parse data and put as IJSonMutableObject, or if parsing fails, it will put it
        /// just as string value of the field.
        /// </summary>
        public RecordedDataSourceResponse RecordBayeuxData(string name, int internalStatus, string channel, string data)
        {
            if (string.IsNullOrEmpty(channel))
            {
                throw new ArgumentNullException("channel");
            }

            var response      = new RecordedBayeuxDataSourceResponse(name);
            var bayeuxMessage = CreateEmptyBayeuxResponse(internalStatus, channel);

            if (string.IsNullOrEmpty(data))
            {
                bayeuxMessage.SetValue("data", data);
            }
            else
            {
                try
                {
                    var reader = new JSonReader(data);
                    bayeuxMessage.SetValue("data", reader.ReadAsJSonMutableObject());
                }
                catch (Exception ex)
                {
                    DebugLog.WriteBayeuxLine("Parsing of 'data' for RecordedBayeuxDataSourceResponse failed!");
                    DebugLog.WriteBayeuxException(ex);

                    bayeuxMessage.SetValue("data", data);
                }
            }

            response.AsJSon = bayeuxMessage;

            Record(response);
            return(response);
        }
Esempio n. 11
0
        public void ParseNullKeyword()
        {
            var reader = new JSonReader("   null");
            var result = reader.ReadAsJSonObject();

            Assert.AreEqual(result.StringValue, null, "Expected a null string!");
        }
Esempio n. 12
0
        public void ParseSimpleData1()
        {
            var reader = new JSonReader("  { \"A\":1, \"B\": 2   , \"c\": 12.1 } ");
            var result = reader.Read();

            AssertExt.IsInstanceOf <IDictionary>(result, "Item should be a dictionary");
        }
Esempio n. 13
0
        public void ParseEmptyArray()
        {
            var reader = new JSonReader("  [    ]");
            var result = reader.Read();

            AssertExt.IsInstanceOf <Array>(result, "Result should be an array");
        }
Esempio n. 14
0
        public void ParseKeyword()
        {
            var reader = new JSonReader("  null  ");
            var result = reader.Read();

            AssertExt.IsInstanceOf <DBNull>(result, "Item should be null");
        }
Esempio n. 15
0
        public void ParseNumberWithForcedFormat()
        {
            var reader = new JSonReader();

            var result1  = reader.ReadAsJSonObject("[12, 13, 14]", JSonReaderNumberFormat.AsInt32);
            var result2  = reader.ReadAsJSonObject("[" + (uint.MaxValue + 1ul) + ", " + (uint.MaxValue + 2ul) + ", " + (uint.MaxValue + 3ul) + "]", JSonReaderNumberFormat.AsInt64);
            var result3  = reader.ReadAsJSonObject("[12.12, 13.13, 14.14]", JSonReaderNumberFormat.AsDouble);
            var result4  = reader.ReadAsJSonObject("[12.12, 13.13, 14.14]", JSonReaderNumberFormat.AsDecimal);
            var result5  = reader.Read("[12, 13, 14]", JSonReaderNumberFormat.AsInt32);
            var result6  = reader.Read("[" + (uint.MaxValue + 1ul) + ", " + (uint.MaxValue + 2ul) + ", " + (uint.MaxValue + 3ul) + "]", JSonReaderNumberFormat.AsInt64);
            var result7  = reader.Read("[12.12, 13.13, 14.14]", JSonReaderNumberFormat.AsDouble);
            var result8  = reader.Read("[12.12, 13.13, 14.14]", JSonReaderNumberFormat.AsDecimal);
            var result9  = reader.ReadAsJSonMutableObject("[12, 13, 14]", JSonReaderNumberFormat.AsInt32);
            var result10 = reader.ReadAsJSonMutableObject("[" + (uint.MaxValue + 1ul) + ", " + (uint.MaxValue + 2ul) + ", " + (uint.MaxValue + 3ul) + "]", JSonReaderNumberFormat.AsInt64);
            var result11 = reader.ReadAsJSonMutableObject("[12.12, 13.13, 14.14]", JSonReaderNumberFormat.AsDouble);
            var result12 = reader.ReadAsJSonMutableObject("[12.12, 13.13, 14.14]", JSonReaderNumberFormat.AsDecimal);

            Assert.IsNotNull(result1);
            Assert.IsNotNull(result2);
            Assert.IsNotNull(result3);
            Assert.IsNotNull(result4);
            Assert.IsNotNull(result5);
            Assert.IsNotNull(result6);
            Assert.IsNotNull(result7);
            Assert.IsNotNull(result8);
            Assert.IsNotNull(result9);
            Assert.IsNotNull(result10);
            Assert.IsNotNull(result11);
            Assert.IsNotNull(result12);
        }
Esempio n. 16
0
        public void ParseEmptyJSonString()
        {
            var reader = new JSonReader("  ");
            var result = reader.Read();

            Assert.IsNull(result, "Result should be null");
        }
    public void SendEvent(string json)
    {
        JSonReader reader = new JSonReader();
        IJSonObject jsonObj = reader.ReadAsJSonObject(json);

        if (jsonObj.Contains("method") && jsonObj.Contains("parameters"))
        {
            switch (jsonObj["method"].ToString())
            {
                case ("PlatformEvent"):
                    if (jsonObj["parameters"].Contains("eventName"))
                        SendMessageToSupport("PlatformEvent", jsonObj["parameters"]["eventName"].ToString());
                    break;
                case ("LowFeedback"):
                    if (jsonObj["parameters"].Contains("message"))
                        if (null != interfaces)
                            interfaces.SendMessage("ShowLowFeedback", jsonObj["parameters"]["message"].ToString(), SendMessageOptions.DontRequireReceiver);
                    break;
                case ("HighFeedback"):
                    if (jsonObj["parameters"].Contains("message"))
                        if (null != interfaces)
                            interfaces.SendMessage("ShowHighFeedback", jsonObj["parameters"]["message"].ToString(), SendMessageOptions.DontRequireReceiver);
                    break;
                case ("Highlight"):
                    if (jsonObj["parameters"].Contains("target"))
                        if (null != workspace)
                            workspace.SendMessage("Highlight", jsonObj["parameters"]["target"].ToString(), SendMessageOptions.DontRequireReceiver);
                    break;
                case ("RemoveHighlight"):
                    if (null != workspace)
                        workspace.SendMessage("DestroyHighlight", SendMessageOptions.DontRequireReceiver);
                    break;
            }
        }
    }
Esempio n. 18
0
        public void ParseEmptyObject()
        {
            var reader = new JSonReader("  { } ");
            var result = reader.Read();

            AssertExt.IsInstanceOf <IDictionary>(result, "Item should be a dictionary");
        }
Esempio n. 19
0
        public void ParseString()
        {
            var reader = new JSonReader("  \"Paweł\\r\\nJSON\\r\\nText\ttab\tspaced.\"  ");
            var result = reader.Read();

            AssertExt.IsInstanceOf <string>(result, "Item should be a string");
        }
Esempio n. 20
0
        public void TestSerializeAndDeserializeViaSimpleAttributes()
        {
            SampleAttributedClass o1 = new SampleAttributedClass("Paweł", 20);

            writer.Write(o1);
            var result = writer.ToString();

            Assert.IsNotNull(result, "Expected some serialized data");
            Assert.IsFalse(result.Contains(SampleAttributedClass.Text), "Unexpected 'const' field in serialized output");
            Assert.IsTrue(result.Contains("StaticSampleField"), "Expected static field in output");

            SampleAttributedClass.StaticSampleField = true;
            var reader = new JSonReader(writer.ToString());
            var o2     = reader.ReadAsJSonObject().ToObjectValue <SampleAttributedClass>();

            Assert.IsNotNull(o2, "Correct value expected");
            Assert.AreEqual(o2.Name, o1.Name, "Name is not equal expected value");
            Assert.AreEqual(o2.Age, o1.Age, "Age is not equal expected value");
            Assert.AreEqual(o2.Address, "default", "Address should be equal to default value");

            // try to load array of elements:
            reader = new JSonReader("[" + result + "]");
            var o3 = reader.ReadAsJSonObject().ToObjectValue <IList <SampleAttributedClass> >();

            Assert.IsNotNull(o3, "Expected data to be read");

            o2 = o3[0];
            Assert.IsNotNull(o2, "Correct value expected");
            Assert.AreEqual(o2.Name, o1.Name, "Name is not equal expected value");
            Assert.AreEqual(o2.Age, o1.Age, "Age is not equal expected value");
            Assert.AreEqual(o2.Address, "default", "Address should be equal to default value");
        }
Esempio n. 21
0
        public void ConvertImmutableJSonObjectToMutableAndUpdateIt()
        {
            var jsonText = "{ \"a\": 1, \"b\": 2, \"c\": [1,2,3,4] }";

            var reader = new JSonReader(jsonText);
            var result = reader.ReadAsJSonObject();

            Assert.IsNotNull(result, "Invalid data read!");
            Assert.AreEqual(1, result["a"].Int32Value, "Unexpected value for field 'a'.");

            var clone = result.CreateMutableClone();

            Assert.IsNotNull(clone, "Unexpected null clone!");
            Assert.AreEqual(1, clone["a"].Int32Value, "Unexpected value for clonned field 'a'.");
            Assert.IsTrue(clone["a"].IsMutable, "Value should be mutable!");

            clone["a"].AsMutable.SetValue(3);
            clone.SetValue("b", 4);
            clone["c"].AsMutable.SetValueAt(2, 55);
            Assert.AreEqual(3, clone["a"].Int32Value, "Expected value to be updated for field 'a'!");
            Assert.AreEqual(4, clone["b"].Int32Value, "Expected value to be updated for field 'b'!");
            Assert.AreEqual(55, clone["c"][2].Int32Value, "Expected array item to be updated!");

            // verify, that original object was left intact:
            Assert.AreEqual(1, result["a"].Int32Value, "Unexpected update!");
            Assert.AreEqual(2, result["b"].Int32Value, "Unexpected update!");
            Assert.AreEqual(3, result["c"][2].Int32Value, "Unexpected update!");
        }
Esempio n. 22
0
        public void ParseDecimalGivenAsString2()
        {
            var reader = new JSonReader("\"12312.3456\"");
            var result = reader.ReadAsJSonObject().DecimalValue;

            AssertExt.IsInstanceOf <decimal>(result, "Item should be a number");
            Assert.AreEqual(result, new Decimal(12312.3456));
        }
Esempio n. 23
0
        public void ParseNumberInt64()
        {
            var reader = new JSonReader("  " + Int64.MaxValue + "  ");
            var result = reader.Read();

            AssertExt.IsInstanceOf <Int64>(result, "Item should be a number");
            Assert.AreEqual(Int64.MaxValue, result);
        }
Esempio n. 24
0
        public void ParseNumber()
        {
            var reader = new JSonReader("  10.1e-2  ");
            var result = reader.Read();

            AssertExt.IsInstanceOf <double>(result, "Item should be a number");
            Assert.AreEqual(result, 10.1e-2);
        }
Esempio n. 25
0
        public void ToStringWithInvalidFormat()
        {
            var reader = new JSonReader("[1, 2, 3, [\"a\", \"b\", \"c\", [4, 5, 6, [{\"f\": 1, \"x\": 2}]]]]");
            var data   = reader.ReadAsJSonObject();

            Assert.IsNotNull(data);
            data.ToString("xxl");
        }
Esempio n. 26
0
        public void ParseValidUnicodeCharacterInString()
        {
            var reader = new JSonReader("  \"\\u0020\"");
            var result = reader.Read();

            AssertExt.IsInstanceOf <string>(result, "Item should be string");
            Assert.AreEqual(" ", result, "Single space was provided as input!");
        }
Esempio n. 27
0
        public void ParseDateWithoutTimeAsUnspecified()
        {
            var reader = new JSonReader("\"1999-01-07\"");
            var item   = reader.ReadAsJSonObject();
            var date   = item.DateTimeValue;

            Assert.AreEqual(new DateTime(1999, 01, 07, 0, 0, 0, DateTimeKind.Unspecified), date);
        }
Esempio n. 28
0
        public void ParseISODateWithoutTimeZone()
        {
            var reader = new JSonReader("\"2012-05-17 09:58:33\"");
            var item   = reader.ReadAsJSonObject();
            var date   = item.DateTimeValue;

            Assert.AreEqual(new DateTime(2012, 05, 17, 09, 58, 33, DateTimeKind.Local), date);
        }
Esempio n. 29
0
        public void ParseCorrectlyTooLongUnicodeCharacterDefinitionInString()
        {
            var reader = new JSonReader("  \"Text-\\u12345\"");
            var result = reader.Read();

            Assert.IsNotNull(result, "Result can't be null");
            Assert.AreEqual("Text-\u12345", result, "Invalid text read");
        }
Esempio n. 30
0
        public void ParseNumberWithDecimalForced_AndCheckItemType()
        {
            var reader = new JSonReader((ulong.MaxValue + 1d).ToString(CultureInfo.InvariantCulture));
            var result = reader.ReadAsJSonObject(JSonReaderNumberFormat.AsDecimal);

            Assert.IsNotNull(result);
            Assert.IsTrue(result.GetType().Name.Contains("DecimalDecimal"));
        }
Esempio n. 31
0
        public void ParseStringSpecialCharacter()
        {
            var reader = new JSonReader("  \"\\\"\"");
            var result = reader.Read();

            AssertExt.IsInstanceOf <string>(result, "Item should be string");
            Assert.AreEqual("\"", result, "Expected special character!");
        }
Esempio n. 32
0
    public void ProcessTaskInformationPackage(string jsonString)
    {
        JSonReader reader = new JSonReader();
        IJSonObject jsonObj = reader.ReadAsJSonObject(jsonString);
        elements = new List<Element>();

        ParseInitialModel(jsonObj);
        ParseInitialConfiguration(jsonObj);
        ParseExtraInformation(jsonString);
         taskDescriptionIsActive = ParseTaskDescription(jsonObj);
    }
    //Wating for a request
    IEnumerator WaitForRequest(WWW URLConnection, WWWForm FaceForm)
    {
        yield return new WaitForSeconds (5);
        yield return URLConnection;
        yield return FaceForm;
        //Exception to control the web service connection
        if(URLConnection.error == null)
        {
            Debug.Log (URLConnection.text);
            Debug.Log ("The Connection would be in a few seconds…" + URLConnection.progress);
            Debug.Log ("Succesful Connection");

            //Flags for watch the expected beahavior
            jSonReader = new JSonReader (URLConnection.text);
            Debug.Log ("Tengo esto: " + jSonReader.jsonString);
            Debug.Log ("Triste es igual a… " + jSonReader.EmotionVal1);
            Debug.Log ("Neutral es igual a… " + jSonReader.EmotionVal2);
            Debug.Log ("Enojado es igual a… " + jSonReader.EmotionVal3);
            Debug.Log ("Sorprendido es igual a… " + jSonReader.EmotionVal4);
            Debug.Log ("Miedo es igual a… " + jSonReader.EmotionVal5);
            Debug.Log ("Felicidad es igual a… " + jSonReader.EmotionVal6);
            //Getting the conclusion and setting the mood
            Mood = jSonReader.GetMoodConclusion();
            setMood(Mood);
            //Sending the mood to the invoker
            storyTellerInvoker.GetComponent<StoryTellerInvoker>().setMood(Mood);
            //The powerful trafficlights
            TrafficLights.stopAndPlay = 0;
            TrafficLights.stopCommand = 0;
            Debug.Log ("la variable de storyTellerInvoker tiene: " + storyTellerInvoker.GetComponent<StoryTellerInvoker>().getMood());
        }
        else
        {
            //Message error: When the Web service couldn't connect
            Debug.Log("Whoops!!! There was a little problem: " + URLConnection.error);
        }
        //Reading photos
        CounterSnaps++;
        string currentURL = PhotoLocation + CounterSnaps + ".jpg";
        MakeFaceRequest (currentURL);
    }
Esempio n. 34
0
	// Obtem o resultado do vinculo com o Facebook
	private IEnumerator handleLink()
	{
#if UNITY_IPHONE
		EtceteraBinding.hideActivityView();
#elif UNITY_ANDROID
		EtceteraAndroid.hideProgressDialog();
#endif
		//GameGUI.game_native.stopLoading();
		
		// Numero maximo de tentativas
		int max_attempts = 5;
		
		WWW conn = null;
		
		WWWForm form = new WWWForm();
		form.AddField("token", Save.GetString(PlayerPrefsKeys.TOKEN.ToString()));
		form.AddField("device", SystemInfo.deviceUniqueIdentifier.Replace("-",""));
		
		while (max_attempts > 0)
		{
			conn = new WWW(Flow.URL_BASE + "login/facebook/fblresult.php", form);
			yield return conn;
			
			if (conn.error != null || conn.text != "") break;
			
			max_attempts--;
			yield return new WaitForSeconds(1);
		}
		
		if (max_attempts == 0 || conn.error != null)
		{
			Debug.LogError("Server error: " + conn.error);
			sendToCallback(GameJsonAuthConnection.DEFAULT_ERROR_MESSAGE, null);
			
			yield break;
		}
		
		JSonReader reader = new JSonReader();
		IJSonObject data = reader.ReadAsJSonObject(conn.text);
		
		// Salva o token
		if (data.Contains("token")) GameToken.save(data);
		
		// Verifica se houve erro
		if (data == null || data.Contains("error"))
		{
			Debug.LogError("Json error: " + conn.text);
			
			string message;
			
			switch(data["error"].ToString())
			{
				case "access_denied":
					message = "You have to authorize our app on Facebook.";
					break;
					
				case "facebook_already_used":
					message = "Your Facebook is already in use on another account.";
					break;
					
				case "different_account":
					message = "Your account already has another Facebook linked.";
					break;
				
				default:
					message = GameJsonAuthConnection.DEFAULT_ERROR_MESSAGE;
					break;
			}
			
			sendToCallback(message, null);
			yield break;
		}
		
		data = data["result"];
		
		Save.Set(PlayerPrefsKeys.FACEBOOK_TOKEN.ToString() , data["fbtoken"].ToString(), true);
		sendToCallback(null, data);
	}
	// Convida os amigos a partir do canvas
	public void inviteFriendsFromCanvas(string request)
	{
		if (request.IsEmpty())
		{
			Debug.Log("empty request");
			//Scene.First.Load();
			return;
		}
		
		JSonReader reader = new JSonReader();
		IJSonObject json = null;
		
		// Tenta ler o retorno
		try
		{
			json = reader.ReadAsJSonObject(request);
		}
		catch (JSonReaderException e)
		{
			Debug.Log("exception: "+e.Message);
			//Scene.First.Load();
			return;
		}
		
		GameJsonAuthConnection conn = new GameJsonAuthConnection(Flow.URL_BASE + "login/facebook/invite.php", handleInviteFriendsFromCanvas);
		
		WWWForm form = new WWWForm();
		form.AddField("request", json["request"].StringValue);
		form.AddField("redirect", "no");
		
		int i = 0;
		foreach (IJSonObject friend in json["to"].ArrayItems)
		{
			form.AddField("to[" + i + "]", friend.StringValue);
			i++;
		}
		
		conn.connect(form);
	}
Esempio n. 36
0
	// Obtem as informacoes do Facebook no servidor
	private IEnumerator getLoginResult(string auth, object state, LoginCallback callback)
	{
		// Numero maximo de tentativas
		int max_attempts = 5;
		
		WWW conn = null;
		
		WWWForm form = new WWWForm();
		form.AddField("device", SystemInfo.deviceUniqueIdentifier.Replace("-", ""));
		form.AddField("authentication", auth);
		
		while (max_attempts > 0)
		{
			conn = new WWW(Flow.URL_BASE + "login/facebook/fbinfo.php", form);
			yield return conn;
			
			if (conn.error != null || conn.text != "") break;
			
			max_attempts--;
			
			yield return new WaitForSeconds(1);
		}
		
		if (max_attempts == 0 || conn.error != null)
		{
			Debug.LogError("Server error: " + conn.error);
			yield break;
		}
		
		JSonReader reader = new JSonReader();
		IJSonObject data = reader.ReadAsJSonObject(conn.text);
		
		if (data == null || data.Contains("error"))
		{
			Debug.LogError("Json error: " + conn.text);
			yield break;
		}
		
		GameToken.save(data);
		
		// Verifica se houve erro
		if (data.Contains("fb_error_reason") && data["fb_error_reason"].ToString() == "user_denied")
		{
			// Up Top Fix Me
			//GameGUI.game_native.showMessage("Error", "You need to authorize our app on Facebook.");
			
			// Redireciona para o login caso necessario
			// Up Top Fix Me
			//if (Scene.GetCurrent() != GameGUI.components.login_scene)
				//Scene.Login.Load(Info.firstScene);
			
			yield break;
		}
		
		// Salva o token do Facebook
		Save.Set(PlayerPrefsKeys.FACEBOOK_TOKEN.ToString(), data["fbtoken"].ToString(), true);		
		
		// Atualiza token da FacebookAPI
		FacebookAPI facebook = new FacebookAPI();
		facebook.UpdateToken();
		if (callback != null) callback(state);
	}
	private void handleLoginFromCanvas(string error, WWW data)
	{
		// Up Top Fix Me
		//GameGUI.enableGui();
		//game_native.stopLoading();
		
		Debug.Log("esta acontecendo: "+data.text);
		
		JSonReader reader = new JSonReader();
		IJSonObject json = null;
		
		// Tenta ler o retorno
		try
		{
			if (error == null) json = reader.ReadAsJSonObject(data.text);
		}
		catch (JSonReaderException e)
		{
			Debug.Log(e.StackTrace);
			Debug.Log(e.Source);
			Debug.Log(e.InnerException);
			Debug.Log(e.Message);
			error = MESSAGE_LOGIN_FAILED;
		}
		
		//Debug.Log(json);
		
		if (error != null || json == null || !json["logged"].BooleanValue)
		{
			Debug.Log(error);
			// Up Top Fix Me
			//game_native.showMessage("Error", MESSAGE_LOGIN_FAILED);
			return;
		}
		
		Save.Set(PlayerPrefsKeys.TOKEN.ToString(), json["token"].ToString());
		Save.Set(PlayerPrefsKeys.NAME.ToString(), json["username"].ToString());
		Save.Set(PlayerPrefsKeys.ID.ToString(), json["user_id"].ToString());
		
		Save.Set(PlayerPrefsKeys.FIRST_NAME.ToString(), json["first_name"].ToString());
		Save.Set(PlayerPrefsKeys.LAST_NAME.ToString(), json["last_name"].ToString());
		Save.Set(PlayerPrefsKeys.LOCATION.ToString(), json["location"].ToString());
		if(!json["gender"].IsNull) Save.Set(PlayerPrefsKeys.GENDER.ToString(), json["gender"].ToString());
		string day, month, year;
		string[] separator = {"-"};
		string[] birthday = json["birthday"].StringValue.Split(separator,System.StringSplitOptions.None);
		
		day = birthday[2];
		month = birthday[1];
		year = birthday[0];
		
		Save.Set(PlayerPrefsKeys.DATE_DAY.ToString(), day);
		Save.Set(PlayerPrefsKeys.DATE_MONTH.ToString(), month);
		Save.Set(PlayerPrefsKeys.DATE_YEAR.ToString(), year);
		
		Debug.Log(json);
		
		// Se a conta nao for nova, redireciona a cena
		if (!json["new_account"].BooleanValue) 
		{
			Debug.Log("conta velha");
			//Scene.First.Load();
		}
		else 
		{
			Debug.Log("conta nova");
			Application.ExternalEval("inviteFriends()");
		}
		
		ConfigManager.offlineUpdater.UpdateOfflineItems();
	}
Esempio n. 38
0
	// Obtem as informacoes do Facebook no servidor
	private IEnumerator getFacebookInfo()
	{
		Debug.Log("pegando info face");
		// Numero maximo de tentativas
		int max_attempts = 5;
		
		WWW conn = null;
		
		WWWForm form = new WWWForm();
		form.AddField("device", SystemInfo.deviceUniqueIdentifier.Replace("-", ""));
		form.AddField("authentication", authentication);
		
		while (max_attempts > 0)
		{
			conn = new WWW(Flow.URL_BASE + "login/facebook/fbinfo.php", form);
			yield return conn;
			
			if (conn.error != null || conn.text != "") break;
			
			max_attempts--;
			
			yield return new WaitForSeconds(1);
		}
		
		Flow.game_native.stopLoading();
		
		if (max_attempts == 0 || conn.error != null)
		{
			Debug.LogError("Server error: " + conn.error);
			Flow.game_native.showMessage("Error", GameJsonAuthConnection.DEFAULT_ERROR_MESSAGE);
			
			yield break;
		}
		
		JSonReader reader = new JSonReader();
		IJSonObject data = reader.ReadAsJSonObject(conn.text);
		
		if (data == null || data.Contains("error"))
		{
			Debug.LogError("Json error: " + conn.text);
			Flow.game_native.showMessage("Error", GameJsonAuthConnection.DEFAULT_ERROR_MESSAGE);
			
			yield break;
		}
		
		Debug.Log("data: " + data);
		
		GameToken.save(data);
		Save.Set(PlayerPrefsKeys.FACEBOOK_TOKEN.ToString(), data["fbtoken"].ToString(), true);
		Save.Set(PlayerPrefsKeys.NAME.ToString(), data["username"].ToString(),true);
		Save.Set(PlayerPrefsKeys.ID.ToString(), data["user_id"].ToString(),true);
		if(!data["email"].IsNull) Save.Set(PlayerPrefsKeys.EMAIL.ToString(), data["email"].ToString(), true);
		if(!data["first_name"].IsNull) Save.Set(PlayerPrefsKeys.FIRST_NAME.ToString(), data["first_name"].ToString(), true);
		if(!data["last_name"].IsNull) Save.Set(PlayerPrefsKeys.LAST_NAME.ToString(), data["last_name"].ToString(), true);
		if(!data["location"].IsNull) Save.Set(PlayerPrefsKeys.LOCATION.ToString(), data["location"].ToString(), true);
		if(!data["gender"].IsNull) Save.Set(PlayerPrefsKeys.GENDER.ToString(), data["gender"].ToString(), true);
		
		if(!data["birthday"].IsNull)
		{
			string day, month, year;
			string[] separator = {"-"};
			string[] birthday = data["birthday"].StringValue.Split(separator,System.StringSplitOptions.None);
			
			day = birthday[2];
			month = birthday[1];
			year = birthday[0];
			
			Save.Set(PlayerPrefsKeys.DATE_DAY.ToString(), day,true);
			Save.Set(PlayerPrefsKeys.DATE_MONTH.ToString(), month,true);
			Save.Set(PlayerPrefsKeys.DATE_YEAR.ToString(), year,true);
		}
		
		// Atualiza token da FacebookAPI
		if (Save.HasKey(PlayerPrefsKeys.FACEBOOK_TOKEN.ToString())) {
			FacebookAPI facebook = new FacebookAPI();
			facebook.SetToken(Save.GetString(PlayerPrefsKeys.FACEBOOK_TOKEN.ToString()));
		}
		
		Save.SaveAll();
		
		ConfigManager.offlineUpdater.UpdateOfflineItems();
		
		CheckLogin();
	}
Esempio n. 39
0
	// Processa o resultado da conexao de login
	private void connectionResult(string error, WWW data)
	{
		//Debug.Log("resultado chegou");
		JSonReader reader = new JSonReader();
		IJSonObject json = null;
		
		//Debug.Log("data: "+data.text);
		
		// Tenta ler o retorno
		if (data == null) error = "json_error";
		else
		{
			try
			{
				if (error == null) json = reader.ReadAsJSonObject(data.text);
			}
			catch (JSonReaderException)
			{
				error = "json_error";
			}
		}
		
		// Verifica se houve erro
		if (error == null && json.Contains("error")) error = json["error"].ToString();
		
		Flow.game_native.stopLoading();
		
		// Trata o erro
		if (error != null)
		{
			switch (error)
			{
				case "empty_email": error = "Please inform an e-mail."; break;
				case "invalid_email": error = "Invalid e-mail. Please try another account."; break;
				default: error = GameJsonAuthConnection.DEFAULT_ERROR_MESSAGE; break;
			}
			Flow.game_native.showMessage("Error", error);
			
			return;
		}
		
		if (json.Contains("ask") && json["ask"].ToString() == "password")
		{			
			passwordDialog.SetActive(true);
			UIManager.instance.FocusObject = passwordField;
			
			return;
		}
		
		Debug.Log(json);
		
		GameToken.save(json);
		Save.Set(PlayerPrefsKeys.EMAIL.ToString(), email,true);
		Save.Set(PlayerPrefsKeys.PASSWORD.ToString(), password, true);
		
		Save.Set(PlayerPrefsKeys.NAME.ToString(), json["username"].ToString(),true);
		Save.Set(PlayerPrefsKeys.ID.ToString(), json["user_id"].ToString(),true);
		
		if(!json["first_name"].IsNull) Save.Set(PlayerPrefsKeys.FIRST_NAME.ToString(), json["first_name"].ToString(), true);
		if(!json["last_name"].IsNull) Save.Set(PlayerPrefsKeys.LAST_NAME.ToString(), json["last_name"].ToString(), true);
		if(!json["location"].IsNull) Save.Set(PlayerPrefsKeys.LOCATION.ToString(), json["location"].ToString(), true);
		if(!json["gender"].IsNull) Save.Set(PlayerPrefsKeys.GENDER.ToString(), json["gender"].ToString(), true);
		if(!json["birthday"].IsNull)
		{
			string day, month, year;
			string[] separator = {"-"};
			string[] birthday = json["birthday"].StringValue.Split(separator,System.StringSplitOptions.None);
			
			day = birthday[2];
			month = birthday[1];
			year = birthday[0];
			
			Save.Set(PlayerPrefsKeys.DATE_DAY.ToString(), day,true);
			Save.Set(PlayerPrefsKeys.DATE_MONTH.ToString(), month,true);
			Save.Set(PlayerPrefsKeys.DATE_YEAR.ToString(), year,true);
		}
		
		
		
		// Verifica se possui Facebook
		if (json.Contains("fbtoken") && json.Contains("facebook_id"))
		{
			Save.Set(PlayerPrefsKeys.FACEBOOK_TOKEN.ToString(), json["fbtoken"].ToString(), true);
			Save.Set(PlayerPrefsKeys.FACEBOOK_ID.ToString(), json["facebook_id"].ToString(), true);
		}
		
		// Atualiza token da FacebookAPI
		if (Save.HasKey(PlayerPrefsKeys.FACEBOOK_TOKEN.ToString())) 
		{
			FacebookAPI facebook = new FacebookAPI();
			facebook.SetToken(Save.GetString(PlayerPrefsKeys.FACEBOOK_TOKEN.ToString()));
		}
		
		ConfigManager.offlineUpdater.UpdateOfflineItems();
		
		// Verifica se e uma conta nova
		if (json["new_account"].ToString() != "0")
		{						
			//messageOkDialog.transform.FindChild("ConfirmButtonPanel").FindChild("ConfirmButton").GetComponent<UIButton>().methodToInvoke = "BringInInvite";
			Flow.game_native.showMessage("Hello!", "Hi! You've registered with us! We've emailed you your password.");
			return;
		}
		
		
		
		
		
		// Redireciona a proxima cena
		
		panelManager.BringIn("MultiplayerScenePanel");
	}
Esempio n. 40
0
	public static IJSonObject ToJSon(this string value)
    {
		JSonReader reader = new JSonReader();
		
		try
		{
			IJSonObject data = reader.ReadAsJSonObject(value);
			return data;
		}
		catch (JSonReaderException)
		{
			return reader.ReadAsJSonObject(ERROR_INVALID_JSON);
		}
    }