Esempio n. 1
0
            public void readJsonfromGoogle(string txt)
            {
                JsonReader jsonReader = new JsonReader();
                Dictionary<string, object> dictionary = (Dictionary<string, object>)jsonReader.Read(txt);
                dictionary = (Dictionary<string, object>)dictionary["feed"];
                Dictionary<string, object>[] entrys = (Dictionary<string, object>[])dictionary["entry"];
                for (int i = 0; i < entrys.GetLength(0); i++)
                {
                    /*for (int j = 0; j < 4; j++)
                    {
                        dictionary = (Dictionary<string, object>)entrys[i]["gsx$r"+(j+1)];
                        Console.WriteLine((string)dictionary["$t"]);
                    
                    }*/

                    dictionary = (Dictionary<string, object>)entrys[i]["gsx$r1"];
                    if (((string)dictionary["$t"]).ToLower() == "version")
                    {
                        dictionary = (Dictionary<string, object>)entrys[i]["gsx$r2"];
                        this.newestversion=(string)dictionary["$t"];
                        Console.WriteLine("version string recived");
                    }

                }
            }
Esempio n. 2
0
        public void handleMessage(Message msg)
        {

            if (msg is CardTypesMessage)
            {
                JsonReader jsonReader = new JsonReader();
                Dictionary<string, object> dictionary = (Dictionary<string, object>)jsonReader.Read(msg.getRawText());
                Dictionary<string, object>[] d = (Dictionary<string, object>[])dictionary["cardTypes"];

                this.cardids = new int[d.GetLength(0)];
                this.cardnames = new string[d.GetLength(0)];
                this.cardImageid = new int[d.GetLength(0)];

                for (int i = 0; i < d.GetLength(0); i++)
                {
                    cardids[i] = Convert.ToInt32(d[i]["id"]);
                    cardnames[i] = d[i]["name"].ToString();
                    cardImageid[i] = Convert.ToInt32(d[i]["cardImage"]);
                }
                
                App.Communicator.removeListener(this);//dont need the listener anymore
            }
            
            return;
        }
Esempio n. 3
0
        /// <summary>
        /// Deserialize the specified message using either JSONFX or NEWTONSOFT.JSON.
        /// The functionality is based on the pre-compiler flag
        /// </summary>
        /// <param name="message">Message.</param>
        public static T Deserialize <T> (string message)
        {
            object retMessage;

                                                #if (USE_JSONFX) || (USE_JSONFX_UNITY)
            var reader = new JsonFx.Json.JsonReader();
            retMessage = reader.Read <T> (message);
                                                #elif (USE_JSONFX_UNITY_IOS)
            UnityEngine.Debug.Log("message: " + message);
            retMessage = JsonReader.Deserialize <T>(message);
                                                #elif (USE_MiniJSON)
            UnityEngine.Debug.Log("message: " + message);
            object retMessage1   = Json.Deserialize(message) as object;
            Type   type          = typeof(T);
            var    expectedType2 = typeof(object[]);
            if (expectedType2.IsAssignableFrom(type))
            {
                retMessage = ((System.Collections.IEnumerable)retMessage1).Cast <object> ().ToArray();
            }
            else
            {
                retMessage = retMessage1;
            }
                                                #else
            retMessage = JsonConvert.DeserializeObject <T> (message);
                                                #endif
            return((T)retMessage);
        }
Esempio n. 4
0
 public static T DeserializeUsingJSONFx<T> (string message)
 {
     object retMessage;
     var reader = new JsonFx.Json.JsonReader ();
     retMessage = reader.Read<T> (message);
     return (T)retMessage;
 }
Esempio n. 5
0
        public List<dynamic> ExtractAppRevenueData(string appName, string queryString)
        {
            var revenueData = DistimoService.GetDistimoData(SupportedDistimoApis.Revenues, queryString);

            var reader = new JsonReader();
            dynamic output = reader.Read(revenueData);

            List<dynamic> filteredList = new List<dynamic>();

            try
            {
                foreach (dynamic line in output.lines)
                {
                    string localAppName = line.data.application;

                    if (localAppName.Contains(appName))
                        filteredList.Add(line);
                }
            }
            catch (RuntimeBinderException)
            {
                // too many requests, try again
                Thread.Sleep(1100);
                return ExtractAppRevenueData(appName, queryString);
            }

            return filteredList;
        }
Esempio n. 6
0
        public void handleMessage(Message msg)
        {
            if (msg is RoomEnterMessage)
            {
                RoomEnterMessage rms = (RoomEnterMessage)msg;
                this.nomssg.Add(rms.roomName);

            }

            if (msg is RoomInfoMessage)
            {
                Console.WriteLine("joinleave bearbeitet: " + msg.getRawText());
                //"removed";
                //"updated";
                JsonReader jsonReader = new JsonReader();
                Dictionary<string, object> dictionary = (Dictionary<string, object>)jsonReader.Read(msg.getRawText());
                string roomname = (string)dictionary["roomName"];

                

                if (msg.getRawText().Contains("removed"))
                {
                    Dictionary<string, object>[] d = (Dictionary<string, object>[])dictionary["removed"];

                    for (int i = 0; i < d.Length; i++)
                    {
                        string ltext = d[i]["name"] + " has left the room";
                        
                        RoomChatMessageMessage leftmessage = new RoomChatMessageMessage(roomname, "<color=#777460>" + ltext + "</color>");
                        App.ChatUI.handleMessage(leftmessage);
                        App.ArenaChat.ChatRooms.ChatMessage(leftmessage);
                    }

                }

                if (msg.getRawText().Contains("updated") && this.nomssg.Contains(roomname))
                {
                    nomssg.RemoveAll(item => item == roomname);
                }
                else
                {
                    if (msg.getRawText().Contains("updated"))
                    {
                        Dictionary<string, object>[] d = (Dictionary<string, object>[])dictionary["updated"];

                        for (int i = 0; i < d.Length; i++)
                        {
                            string ltext = d[i]["name"] + " has joined the room";
                            RoomChatMessageMessage leftmessage = new RoomChatMessageMessage(roomname, "<color=#777460>" + ltext + "</color>");
                            App.ChatUI.handleMessage(leftmessage);
                            App.ArenaChat.ChatRooms.ChatMessage(leftmessage);
                        }

                    }

                }
            }
            
            return;
        }
Esempio n. 7
0
    public override T Deserialize <T>(string text)
    {
        var r   = new JsonFx.Json.JsonReader();
        var s   = Environment.TickCount;
        var ret = r.Read <T>(text);

        DeserializeTimeList.Add(Environment.TickCount - s);
        return(ret);
    }
Esempio n. 8
0
        public static bool tryUpdate()
        {
            WebClientTimeOut client = new WebClientTimeOut ();
            String versionMessageRaw;
            try {
                versionMessageRaw = client.DownloadString (new Uri("http://mods.scrollsguide.com/version"));
            } catch (WebException) {
                return false;
            }

            JsonReader reader = new JsonReader ();
            VersionMessage versionMessage = (VersionMessage)reader.Read (versionMessageRaw, typeof(VersionMessage));

            int version = versionMessage.version ();
            String installPath = Platform.getGlobalScrollsInstallPath () + Path.DirectorySeparatorChar + "ModLoader" + Path.DirectorySeparatorChar;

            try {
                File.Delete (installPath + "Updater.exe");
            } catch {}

            if (!System.IO.Directory.Exists(installPath)) {
                System.IO.Directory.CreateDirectory(installPath);
            }

            if (version > ModLoader.getVersion()) {

                byte[] asm;
                try {
                    asm = client.DownloadData(new Uri("http://mods.scrollsguide.com/download/update"));
                } catch (WebException) {
                    return false;
                }
                File.WriteAllBytes (installPath + "Updater.exe", asm);
                if (CheckToken (installPath + "Updater.exe", token)) {

                    try {
                        App.Popups.ShowInfo ("Scrolls Summoner is updating", "Please wait while the update is being downloaded");
                        Dialogs.showNotification("Scrolls Summoner is updating", "Please wait while the update is being downloaded");
                    } catch { }

                    if (Platform.getOS () == Platform.OS.Win) {
                        new Process { StartInfo = { FileName = installPath + "Updater.exe", Arguments = "" } }.Start ();
                    } else if (Platform.getOS () == Platform.OS.Mac) {
                        Assembly.LoadFrom (installPath + "Updater.exe").EntryPoint.Invoke (null, new object[] { new string[] {} });
                    }
                    return true;
                }

                try {
                    App.Popups.KillCurrentPopup();
                } catch {}
            }

            return false;
        }
Esempio n. 9
0
 /// <summary>
 /// Deserialize the specified message using either JSONFX or NEWTONSOFT.JSON.
 /// The functionality is based on the pre-compiler flag
 /// </summary>
 /// <param name="message">Message.</param>
 public static T Deserialize<T> (string message)
 {
     object retMessage;
     #if (USE_JSONFX)
     var reader = new JsonFx.Json.JsonReader();
     retMessage = reader.Read<T>(message);
     #else
     retMessage = JsonConvert.DeserializeObject<T> (message);
     #endif
     return (T)retMessage;
 }
Esempio n. 10
0
    public static dynamic StringToDynamic(string s)
    {
        if ("" == s)
        {
            return(null);
        }

        JsonFx.Json.JsonReader cReader = new JsonFx.Json.JsonReader();
        dynamic c = cReader.Read(s);

        return(c);
    }
    public void ReadSettings()
    {
        var filePath = new System.IO.FileInfo(ServerDirectory.FullName + "/Server.json");

        if (!filePath.Exists)
        {
            Log.Info("No Server.json, using only commandline args");
            return;
        }
        try
        {
            var txt        = System.IO.File.ReadAllText(filePath.FullName);
            var reader     = new JsonFx.Json.JsonReader();
            var dictionary = (Dictionary <string, object>)reader.Read(txt);

            object[] pluginDirsList = new object[0];
            TryGetValue(dictionary, "PluginsDir", ref pluginDirsList);
            foreach (object dir in pluginDirsList)
            {
                if (dir is string)
                {
                    Log.Debug($"Adding plugin directory: {dir}");
                    pluginDirs.Add(new System.IO.DirectoryInfo((string)dir));
                }
                else
                {
                    Log.Info($"PluginsDir included value that was not a string: {dir}");
                }
            }

            object[] pluginsList = new object[0];
            TryGetValue(dictionary, "Plugins", ref pluginsList);
            foreach (object dir in pluginsList)
            {
                if (dir is string)
                {
                    Log.Debug($"Adding plugin: {dir}");
                    directPluginDirs.Add(new System.IO.FileInfo((string)dir));
                }
                else
                {
                    Log.Info($"Plugins included value that was not a string: {dir}");
                }
            }

            Log.Info("Loaded settings from Server.json");
        }
        catch (Exception e)
        {
            Log.Error($"Couldn't read Server.json. Is your json malformed?\n{e}");
        }
    }
Esempio n. 12
0
        public void Encode()
        {
            var id = new InstrumentData() { Pitch = 31, Roll = 89 };

            var x = new JsonWriter();
            var js = x.Write(id);

            var y = new JsonReader();
            var decoded = y.Read<InstrumentData>(js);

            Assert.AreEqual(id.Roll, decoded.Roll);
            Assert.AreEqual(id.Pitch, decoded.Pitch);
        }
Esempio n. 13
0
 public ExportationOptions CreateSettings()
 {
     ExportationOptions result = new ExportationOptions();
     string apath = Application.dataPath.Replace("/Assets", "");
     string ufile = Path.Combine(apath, "UnityBabylonOptions.ini");
     if (File.Exists(ufile))
     {
         var readText = File.ReadAllText(ufile);
         var jsReader = new JsonReader();
         result = jsReader.Read<ExportationOptions>(readText);
     }
     return result;
 }
Esempio n. 14
0
        public static JsonPatchDocument Read(TextReader r)
        {
            JsonPatchDocument patch = new JsonPatchDocument();

              JsonReader jsr = new JsonReader();
              CompleteOperation[] operations = null;
              try
              {
            operations = jsr.Read<CompleteOperation[]>(r);
              }
              catch (DeserializationException ex)
              {
            throw new JsonPatchParserException(ex.Message, ex);
              }

              foreach (CompleteOperation operation in operations)
              {
            try
            {
              switch (operation.op)
              {
            case "add":
              patch.Add(operation.path, operation.value);
              break;
            case "remove":
              patch.Remove(operation.path);
              break;
            case "replace":
              patch.Replace(operation.path, operation.value);
              break;
            case "move":
              patch.Move(operation.from, operation.path);
              break;
            case "copy":
              patch.Copy(operation.from, operation.path);
              break;
            case "test":
              patch.Test(operation.path, operation.value);
              break;
            case null:
              throw new JsonPatchParserException("No 'op' property found.");
              }
            }
            catch (ArgumentNullException ex)
            {
              throw new JsonPatchParserException(string.Format("Missing parameter '{0}' for op:'{1}'.", ex.ParamName, operation.op), ex);
            }
              }

              return patch;
        }
Esempio n. 15
0
        void UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show(e.Error.Message, "Error", MessageBoxButton.OK);
                return;
            }
            var reader =
                new JsonReader(
                    new DataReaderSettings(
                        new ConventionResolverStrategy(ConventionResolverStrategy.WordCasing.PascalCase)));

            var result = reader.Read<RunResult>(e.Result);
            _codeEditorViewModel.Output = !string.IsNullOrEmpty(result.CompileError) ? result.CompileError : result.Output;
            _codeEditorViewModel.IsRunning = false;
        }
Esempio n. 16
0
        private static string SendPassword(string username, string encryptedBase64, Dictionary<string, object> loginParams)
        {
            // Send the RSA-encrypted password via POST.
            var webRequest = WebRequest.Create(API_DO_LOGIN) as HttpWebRequest;
            webRequest.Method = "POST";

            var timestamp = loginParams["timestamp"] as string;

            var fields = new NameValueCollection();
            fields.Add("username", username);
            fields.Add("password", encryptedBase64);
            fields.Add("emailauth", String.Empty);
            fields.Add("captchagid", String.Empty);
            fields.Add("captcha_text", String.Empty);
            fields.Add("emailsteamid", String.Empty);
            fields.Add("rsatimestamp", timestamp);

            var query = fields.ConstructQueryString();
            var queryData = Encoding.ASCII.GetBytes(query);

            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.ContentLength = queryData.Length;
            webRequest.CookieContainer = new CookieContainer();

            // Write the request
            using (Stream stream = webRequest.GetRequestStream())
            {
                stream.Write(queryData, 0, queryData.Length);
            }

            // Perform the request
            var response = webRequest.GetResponse() as HttpWebResponse;

            String res;
            using (Stream stream = response.GetResponseStream())
            {
                res = stream.ReadAll();
            }

            response.Close();

            var reader = new JsonReader();
            var results = reader.Read<Dictionary<string, object>>(res);

            return response.Cookies["steamLogin"].Value;
        }
Esempio n. 17
0
        /// <summary>
        /// Deserialize the specified message using either JSONFX or NEWTONSOFT.JSON.
        /// The functionality is based on the pre-compiler flag
        /// </summary>
        /// <param name="message">Message.</param>
        public static T Deserialize <T> (string message)
        {
            object retMessage;

                                                #if (USE_JSONFX) || (USE_JSONFX_UNITY)
            var reader = new JsonFx.Json.JsonReader();
            retMessage = reader.Read <T> (message);
                                                #elif (USE_JSONFX_UNITY_IOS)
            UnityEngine.Debug.Log("message: " + message);
            retMessage = JsonReader.Deserialize <T>(message);
                                                #elif (USE_MiniJSON)
            UnityEngine.Debug.Log("message: " + message);
            retMessage = Json.Deserialize(message) as object;
                                                #else
            retMessage = JsonConvert.DeserializeObject <T> (message);
                                                #endif
            return((T)retMessage);
        }
Esempio n. 18
0
        void OnGUI()
        {
            if (exportationOptions == null)
            {
                exportationOptions = new ExportationOptions();

                if (File.Exists("Unity3D2Babylon.ini"))
                {
                    var readText = File.ReadAllText("Unity3D2Babylon.ini");
                    var jsReader = new JsonReader();
                    exportationOptions = jsReader.Read<ExportationOptions>(readText);
                }
            }

            GUILayout.Label("Exportation options", EditorStyles.boldLabel);
            exportationOptions.ReflectionDefaultLevel = EditorGUILayout.Slider("Reflection default level", exportationOptions.ReflectionDefaultLevel, 0, 1.0f);

            GUILayout.Label("Collisions options", EditorStyles.boldLabel);
            exportationOptions.ExportCollisions = EditorGUILayout.Toggle("Collisions", exportationOptions.ExportCollisions);
            exportationOptions.CameraEllipsoid = EditorGUILayout.Vector3Field("Camera's Ellipsoid:", exportationOptions.CameraEllipsoid);
            exportationOptions.Gravity = EditorGUILayout.Vector3Field("Gravity:", exportationOptions.Gravity);

            EditorGUILayout.Space();
            EditorGUILayout.Space();

            if (GUILayout.Button("Export"))
            {
                Export();
            }

            EditorGUILayout.Space();

            scrollPos = EditorGUILayout.BeginScrollView(scrollPos);

            foreach (var log in logs)
            {
                var bold = log.StartsWith("*");

                GUILayout.Label(bold ? log.Remove(0, 1) : log, bold ? (EditorStyles.boldLabel) : EditorStyles.label);
            }
            EditorGUILayout.EndScrollView();

            Repaint();
        }
Esempio n. 19
0
        void ListDownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error == null && !string.IsNullOrEmpty(e.Result))
            {
                var reader = new JsonReader();

                var result = reader.Read<IEnumerable<string>>(e.Result);
                PopulateMainListBox(result);
            }
            else
            {
                var localFiles = e.UserState as string[];
                if (localFiles != null && localFiles.Length > 0)
                {
                    PopulateMainListBox(localFiles);
                }
                else
                {
                    MessageBox.Show("No Saved code was found.");
                    NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
                }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            string assertion = string.Empty;

            if (!String.IsNullOrEmpty(Request.QueryString["assert"]))
            {
                assertion = Request.QueryString["assert"];
            }

            using (var web = new WebClient())
            {
                // Build the data we're going to POST.
                var data = new NameValueCollection();
                data["assertion"] = assertion;
                //data["audience"] = "http://localhost:55298/"; // Use your web site's URL here.
                data["audience"] = "http://www.miramarcommunitycreche.org.nz/"; // Use your web site's URL here.

                // POST the data to the Persona provider (in this case Mozilla)
                var response = web.UploadValues("https://verifier.login.persona.org/verify", "POST", data);
                var buffer = Encoding.Convert(Encoding.GetEncoding("iso-8859-1"), Encoding.UTF8, response);

                // Convert the response to JSON.
                var tempString = Encoding.UTF8.GetString(buffer, 0, response.Length);
                var reader = new JsonReader();
                dynamic output = reader.Read(tempString);
                if (output.status == "okay")
                {
                    string email = output.email; // Since this is dynamic, convert it to string.
                    Master.CurrentUserName = email;
                    Response.Redirect("/default.aspx");
                }
                else
                {
                    Response.Redirect("/auth/logout.aspx");
                }
            }
        }
        public ActionResult Login(string assertion)
        {
            if (assertion == null)
            {
                // The 'assertion' key of the API wasn't POSTED. Redirect, 
                // or whatever you'd like, to try again.
                return RedirectToAction("Index", "Home");
            }

            using (var web = new WebClient())
            {
                // Build the data we're going to POST.
                var data = new NameValueCollection();
                data["assertion"] = assertion;
                data["audience"] = "http://*****:*****@smith.com","audience":"http://localhost:46758/","expires":1349141963794,"issuer":"login.persona.org"}*/
            }
        }
Esempio n. 22
0
 public static Features FromString(string json)
 {
     var reader = new JsonReader();
     dynamic contents = reader.Read(json);
     Features f = new Features();
     f.imagefile = contents.imagefile;
     //try
     {
         f.intlines = new List<IntLineFeature>();
         foreach (dynamic l in contents.intlines)
         {
             IntLineFeature lf = new IntLineFeature();
             lf.id = l.id;
             int[] line = l.line;
             lf.line.p.X = l.line[0];
             lf.line.p.Y = line[1];
             lf.line.q.X = line[2];
             lf.line.q.Y = line[3];
             f.intlines.Add(lf);
         }
     }
     //catch { } //FIXME: catch the right thing
     return f;
 }
        protected override void OnMessage(MessageEventArgs e)
        {
            var reader = new JsonReader();
            KSPACPackets message = reader.Read<KSPACPackets>(e.Data);
            if (message != null)
            {
                switch (message.t)
                {
                    case 1:
                        ConnectionRequest connReqPacket = reader.Read<ConnectionRequest>(e.Data);

                        Send(connReqPacket.HandlePacket(WSClient.getClient(ID)));
                        break;
                    case 2:
                        ActiveVesselThrottleChange throtChg = reader.Read<ActiveVesselThrottleChange>(e.Data);
                        throtChg.HandlePacket(WSClient.getClient(ID));
                        break;
                    case 3:
                        new ActivateNextStage().HandlePacket(WSClient.getClient(ID));
                        break;
                    case 4:
                        RequestAllVesselData ravd = reader.Read<RequestAllVesselData>(e.Data);
                        Send(ravd.HandlePacket(WSClient.getClient(ID)));
                        break;
                    case 5:
                        // Tis an event
                        ChangeSubscriptionToEvent cste = reader.Read<ChangeSubscriptionToEvent>(e.Data);
                        String sendData = cste.HandlePacket(WSClient.getClient(ID));
                        if (sendData != "") Send(sendData);
                        break;
                    case 6:
                        GetCrossOriginHTML gcoh = reader.Read<GetCrossOriginHTML>(e.Data);
                        gcoh.HandlePacket(WSClient.getClient(ID));
                        break;
                    default:
                        Send(new UnrecognizedCommand(message.t).toJson());
                        break;
                }
            }
        }
Esempio n. 24
0
        private static Dictionary<string, object> GetKeyRSA(string username)
        {
            // First ask the public RSA key for encryption.
            var webRequest = WebRequest.Create(API_RSA_KEY) as HttpWebRequest;
            webRequest.Method = "POST";

            var fields = new NameValueCollection();
            fields.Add("username", username);

            var query = fields.ConstructQueryString();
            byte[] data = Encoding.ASCII.GetBytes(query);

            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.ContentLength = data.Length;

            // Write the request
            using (Stream stream = webRequest.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }

            // Perform the request
            var response = webRequest.GetResponse();

            String res;
            using (Stream stream = response.GetResponseStream())
            {
                res = stream.ReadAll();
            }

            response.Close();

            var reader = new JsonReader();
            var json = reader.Read<Dictionary<string, object>>(res);

            return json;
        }
Esempio n. 25
0
        private void parseJSONResult(String result, String oppName)
        {
            // convert the html data to ApiResultMessage
            JsonReader reader = new JsonReader();
            Message message = reader.Read(result, System.Type.GetType("ApiResultMessage")) as ApiResultMessage;

            ApiResultMessage armsg = (ApiResultMessage)message;

            String chatMsg = "";
            if (armsg.msg.Equals("success")) // api call succeeded
            {
                chatMsg += "Player info: " + armsg.data.name + "\n";
                chatMsg += "Rank: " + armsg.data.rank + "\n";
                chatMsg += "Rating: " + armsg.data.rating + "\n";
                chatMsg += "Games played: " + armsg.data.played + "\n";
                chatMsg += "Games won: " + armsg.data.won + " (" + Math.Round(((float)armsg.data.won / (float)armsg.data.played) * 100) + "%)\n";
            }
            else
            {
                chatMsg = "Couldn't get data for " + oppName + ".";
            }
            MethodInfo mi = typeof(BattleMode).GetMethod("updateChat", BindingFlags.NonPublic | BindingFlags.Instance);

            if (mi != null) // send chat message
            {
                mi.Invoke(bm, new String[] { chatMsg });
            }
            else // can't invoke updateChat
            {
            }
        }
Esempio n. 26
0
        private bool readRepository(string url)
        {
            //normalize it
            Uri urlNorm = new Uri (url);
            url = urlNorm.Host;

            String repoinfo = null;
            try {
                WebClientTimeOut client = new WebClientTimeOut ();
                repoinfo = client.DownloadString (new Uri("http://"+url+"/repoinfo"));
            } catch (WebException ex) {
                Console.WriteLine (ex);
                return false;
            }

            RepoInfoMessage message = null;
            try {
                JsonReader reader = new JsonReader();
                message = reader.Read(repoinfo, typeof(RepoInfoMessage)) as RepoInfoMessage;
            } catch {
                return false;
            }

            if (message == null) {
                return false;
            }

            if (!message.msg.Equals("success")) {
                return false;
            }

            Repo repo = message.data;
            repo.tryToGetFavicon ();
            repositories.Add(repo);

            return this.tryToFetchModList (repo);
        }
Esempio n. 27
0
        public void handleMessage(Message msg)
        { // collect data for enchantments (or units who buff)

            if (msg is CardTypesMessage)
            {

                JsonReader jsonReader = new JsonReader();
                Dictionary<string, object> dictionary = (Dictionary<string, object>)jsonReader.Read(msg.getRawText());
                Dictionary<string, object>[] d = (Dictionary<string, object>[])dictionary["cardTypes"];
                this.cardids = new int[d.GetLength(0)];
                this.cardnames = new string[d.GetLength(0)];
                this.cardImageid = new int[d.GetLength(0)];

                for (int i = 0; i < d.GetLength(0); i++)
                {
                    cardids[i] = Convert.ToInt32(d[i]["id"]);
                    cardnames[i] = d[i]["name"].ToString();
                    cardImageid[i] = Convert.ToInt32(d[i]["cardImage"]);
                }

                //App.Communicator.removeListener(this);//dont need the listener anymore
            }

            if(msg is AbilityInfoMessage)
            {
                AbilityInfoMessage aim = (AbilityInfoMessage)msg;
                if (aim.abilityId == "Move")//aim.isPlayable &&
                {
                    this.showLobbers = TileColor.white;
                    if (aim.unitPosition.color == TileColor.white) this.showLobbers = TileColor.black;

                    
                    this.calculateEnemyLobbers(this.showLobbers);

                }
                this.showLobbers = TileColor.unknown;
            }

            if (msg is CardInfoMessage)
            {
                CardInfoMessage aim = (CardInfoMessage)msg;
                //Console.WriteLine("cardinfo");
                if (aim.card.getPieceKind() == CardType.Kind.CREATURE || aim.card.getPieceKind() == CardType.Kind.STRUCTURE)//aim.isPlayable &&
                {
                    this.mark =true;
                    if (aim.data.selectableTiles.Count >= 1)
                    {
                        //Console.WriteLine("cardinfo " + aim.data.selectableTiles.tileSets[0][0].color);
                        this.showLobbers = aim.data.selectableTiles.tileSets[0][0].color.otherColor();
                        this.calculateEnemyLobbers(this.showLobbers);
                    }

                }
                this.showLobbers = TileColor.unknown;
            }


            return;
        }
Esempio n. 28
0
        public void Read_RecognizesFilters_DeserializesMultipleDateTimeFormats()
        {
            var input = @"[ ""Normal string before"", ""2008-02-29T23:59:59.999Z"", ""\\/Date(1278327077768)\\/"", ""Normal string after""]";
            var expected = new object[]
                {
                    "Normal string before",
                    new DateTime(2008, 2, 29, 23, 59, 59, 999, DateTimeKind.Utc),
                    new DateTime(2010, 7, 5, 10, 51, 17, 768, DateTimeKind.Utc),
                    "Normal string after"
                };

            var reader = new JsonReader(
                new DataReaderSettings(
                    new Iso8601DateFilter { Format=Iso8601DateFilter.Precision.Ticks },
                    new MSAjaxDateFilter()) { AllowTrailingContent = true });

            var actual = reader.Read(input);

            Assert.Equal(expected, actual);
        }
Esempio n. 29
0
        void OnGUI()
        {
            if (exportationOptions == null)
            {
                exportationOptions = new ExportationOptions();

                if (File.Exists("Unity3D2Babylon.ini"))
                {
                    var readText = File.ReadAllText("Unity3D2Babylon.ini");
                    var jsReader = new JsonReader();
                    exportationOptions = jsReader.Read<ExportationOptions>(readText);
                }
            }

            GUILayout.Label("Exportation options", EditorStyles.boldLabel);
            exportationOptions.ReflectionDefaultLevel = EditorGUILayout.Slider("Reflection default level", exportationOptions.ReflectionDefaultLevel, 0, 1.0f);

            EditorGUILayout.Space();
            GUILayout.Label("Collisions options", EditorStyles.boldLabel);
            exportationOptions.ExportCollisions = EditorGUILayout.Toggle("Collisions", exportationOptions.ExportCollisions);

            EditorGUILayout.BeginHorizontal(GUILayout.ExpandHeight(false));
            GUILayout.Label("Camera's Ellipsoid");
            exportationOptions.CameraEllipsoid = EditorGUILayout.Vector3Field("", exportationOptions.CameraEllipsoid, GUILayout.ExpandWidth(false));
            EditorGUILayout.EndHorizontal();
            GUILayout.Space(-16);
            EditorGUILayout.BeginHorizontal();
            GUILayout.Label("Gravity");
            exportationOptions.Gravity = EditorGUILayout.Vector3Field("", exportationOptions.Gravity, GUILayout.ExpandWidth(false));
            EditorGUILayout.EndHorizontal();
            GUILayout.Space(-16);
            EditorGUILayout.Space();
            GUILayout.Label("Physics options", EditorStyles.boldLabel);
            exportationOptions.ExportPhysics = EditorGUILayout.Toggle("Physics", exportationOptions.ExportPhysics);
            EditorGUILayout.Space();
            GUILayout.Label("Shadows options", EditorStyles.boldLabel);
            exportationOptions.ExportShadows = EditorGUILayout.Toggle("Shadows", exportationOptions.ExportShadows);

            EditorGUILayout.Space();
            EditorGUILayout.Space();

            if (GUILayout.Button("Export"))
            {
                Export(false);
            }

            if (WebServer.IsSupported)
            {
                if (GUILayout.Button("Export & Run"))
                {
                    Export(true);
                }
            }

            EditorGUILayout.Space();

            scrollPos = EditorGUILayout.BeginScrollView(scrollPos);

            foreach (var log in logs)
            {
                var bold = log.StartsWith("*");

                GUILayout.Label(bold ? log.Remove(0, 1) : log, bold ? (EditorStyles.boldLabel) : EditorStyles.label);
            }
            EditorGUILayout.EndScrollView();

            Repaint();
        }
Esempio n. 30
0
        private void ParseZenossGroupJSON(String Json)
        {
            //Log.Debug("Results were " + Json);
              JsonReader Reader = new JsonReader();
              try
            {
              Dictionary<string, Object> JsonDict = Reader.Read<Dictionary<string, Object>>(Json);
              Dictionary<string, Object> JsonResults = (Dictionary<string, Object>) JsonDict["result"];
              //Log.Debug("has result");
              Object[] Devs = (Object[]) JsonResults["devices"];
              //Log.Debug("has devices");

              this.DeviceCount = 0;
              this.MaintenanceCount = 0;
              this.Info = 0;
              this.Warning = 0;
              this.Error = 0;

              if ( Devs.Length == 0 )
            {
              //                                   Log.Debug("no devices");
            }
              else
            {
              //                                 Log.Debug(Devs.Length.ToString() + " devices");
              for ( int i = 0 ; i < Devs.Length ; i++ )
                {
                  Dictionary<string, Object> DevJson = (Dictionary<string, Object>) Devs[i];
                  string DevState = (string) DevJson["productionState"];
                  this.DeviceCount = this.DeviceCount + 1;
                  if ( DevState == "maintenance" )
                    {
                      this.MaintenanceCount = this.MaintenanceCount + 1;
                    }
                  Dictionary<string, Object> DevEvents = (Dictionary<string, Object>) DevJson["events"];
                  this.Info = this.Info + ( int ) DevEvents["info"];
                  this.Warning = this.Warning + ( int ) DevEvents["warning"];
                  this.Error = this.Error + ( int ) DevEvents["error"];
                  this.Error = this.Error + ( int ) DevEvents["critical"];
                }
            }
            }
              catch ( System.Exception e )
            {
              //                         Log.Debug( " something awful happened " + e.ToString());
            }
        }
Esempio n. 31
0
        private bool ParseZenossGroupsJSON(String Json)
        {
            //Log.Debug("parsing json " + Json);
              JsonReader Reader = new JsonReader();
              //Log.Debug("what " + Reader.ToString());
              try
            {
              Dictionary<string, Object> JsonDict = Reader.Read<Dictionary<string, Object>>(Json);
              if ( JsonDict.ContainsKey("result") )
            {
              Log.Debug("ok then " + JsonDict["result"].ToString());
              Dictionary<string, Object> JsonResults = (Dictionary<string, Object>) JsonDict["result"];
              Object[] JsonGroups = (Object[]) JsonResults["groups"];

              if ( JsonGroups.Length >= 0 )
                {
                  for ( int i = 0 ; i < JsonGroups.Length ; i++ )
                    {
                      Dictionary <string, Object> GroupJson = (Dictionary<string, Object>) JsonGroups[i];
                      string GroupName = (string) GroupJson["name"];
                      if ( ! GroupContains(GroupName, Groups) )
                        {
                          ZenossGroup g = new ZenossGroup(GroupName);
                          Groups.Add(g);
                        }
                    }
                  return true;
                }
            }
              else
            {
              Log.Error("invalid json?");
            }
            }
              catch (System.Exception e )
            {
              Log.Error("something awful happened " + e.ToString());
            }
              return false;
        }
Esempio n. 32
0
        IEnumerator RetrieveLevel()
        {
            var body    = GenerateWorkshopInfoBody(WorkshopLevelIds);
            var request = new UnityWebRequest(fileDetailsUrl);

            request.uploadHandler             = new UploadHandlerRaw(Encoding.ASCII.GetBytes(body));
            request.downloadHandler           = new DownloadHandlerBuffer();
            request.method                    = UnityWebRequest.kHttpVerbPOST;
            request.uploadHandler.contentType = "application/x-www-form-urlencoded";

            yield return(request.SendWebRequest());

            if (request.isNetworkError || request.isHttpError)
            {
                Finished = true;
                Error    = request.error;
                yield break;
            }

            var reader = new JsonFx.Json.JsonReader();
            Dictionary <string, object> responseJson;

            try
            {
                responseJson = reader.Read <Dictionary <string, object> >(request.downloadHandler.text);
            }
            catch (Exception e)
            {
                Finished = true;
                Error    = e.ToString();
                yield break;
            }

            if (!responseJson.ContainsKey("response"))
            {
                Finished = true;
                Error    = "No response key returned from server";
                yield break;
            }

            var response = (Dictionary <string, object>)responseJson["response"];

            if (!response.ContainsKey("publishedfiledetails"))
            {
                Finished = true;
                Error    = "No publishedfiledetails key returned from server";
                yield break;
            }

            var fileDetails = (object[])response["publishedfiledetails"];
            var index       = 0;

            foreach (var detailBase in fileDetails)
            {
                var detail = (Dictionary <string, object>)detailBase;
                if (!detail.ContainsKey("result") || (int)detail["result"] != 1 || !detail.ContainsKey("title") || !detail.ContainsKey("creator") || !detail.ContainsKey("filename"))
                {
                    continue;
                }
                if (!detail.ContainsKey("publishedfileid") || detail["publishedfileid"].GetType() != typeof(string) || (string)detail["publishedfileid"] == string.Empty)
                {
                    continue;
                }
                if (detail["title"].GetType() != typeof(string))
                {
                    continue;
                }
                if (detail["creator"].GetType() != typeof(string) || (string)detail["creator"] == string.Empty)
                {
                    continue;
                }
                if (detail["filename"].GetType() != typeof(string) || (string)detail["filename"] == "")
                {
                    continue;
                }
                string levelVersion = "";
                if (detail.ContainsKey("time_updated"))
                {
                    DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
                    dtDateTime   = dtDateTime.AddSeconds((int)detail["time_updated"]).ToLocalTime();
                    levelVersion = dtDateTime.ToBinary().ToString();
                }

                var                    difficulty       = LevelDifficulty.Unknown;
                List <string>          difficultyNames  = new List <string>(Enum.GetNames(typeof(LevelDifficulty)));
                List <LevelDifficulty> difficultyValues = new List <LevelDifficulty>((LevelDifficulty[])Enum.GetValues(typeof(LevelDifficulty)));

                List <string> supportedModes = new List <string>();
                if (detail.ContainsKey("tags"))
                {
                    foreach (var tagBase in (object[])detail["tags"])
                    {
                        var tag = (Dictionary <string, object>)tagBase;
                        if (tag.ContainsKey("tag") && (string)tag["tag"] != "Level")
                        {
                            var difficultyIndex = difficultyNames.IndexOf((string)tag["tag"]);
                            if (difficultyIndex != -1)
                            {
                                difficulty = difficultyValues[difficultyIndex];
                            }
                            supportedModes.Add((string)tag["tag"]);
                        }
                    }
                }
                var level = new DistanceLevel()
                {
                    Name = (string)detail["title"],
                    RelativeLevelPath = $"WorkshopLevels/{(string)detail["creator"]}/{(string)detail["filename"]}",
                    // Example: "WorkshopLevels/76561198145035078/a digital frontier.bytes"
                    LevelVersion   = levelVersion,
                    WorkshopFileId = (string)detail["publishedfileid"],
                    GameMode       = DefaultGameMode,
                    SupportedModes = supportedModes.ToArray(),
                    Difficulty     = difficulty,
                };
                ValidLevels.Add(level);
                LevelsByPublishedFileId.Add(level.WorkshopFileId, level);
                index++;
            }
            Finished = true;
        }
Esempio n. 33
0
        public static void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs e)
        {
            if ((e.ExceptionObject as Exception).TargetSite.Module.Assembly.GetName().Name.Equals("UnityEngine")
                || (e.ExceptionObject as Exception).TargetSite.Module.Assembly.GetName().Name.Equals("Assembly-CSharp")
                || (e.ExceptionObject as Exception).TargetSite.Module.Assembly.GetName().Name.Equals("ScrollsModLoader")
                || (e.ExceptionObject as Exception).TargetSite.Module.Assembly.Location.ToLower().Equals(Platform.getGlobalScrollsInstallPath().ToLower())
                || (e.ExceptionObject as Exception).TargetSite.Module.Assembly.Location.Equals("")) { //no location or Managed => mod loader crash

                //log
                Console.WriteLine (e.ExceptionObject);
                new ExceptionLogger ().logException ((Exception)e.ExceptionObject);

                //unload ScrollsModLoader
                MethodBodyReplacementProviderRegistry.SetProvider (new NoMethodReplacementProvider());

                //check for frequent crashes
                if (!System.IO.File.Exists (Platform.getGlobalScrollsInstallPath () + System.IO.Path.DirectorySeparatorChar + "check.txt")) {
                    System.IO.File.CreateText (Platform.getGlobalScrollsInstallPath () + System.IO.Path.DirectorySeparatorChar + "check.txt");
                    Platform.RestartGame ();
                } else {
                    try {
                        foreach (String id in instance.modOrder) {
                            BaseMod mod = instance.modInstances [id];
                            if (mod != null) {
                                try {
                                    instance.unloadMod((LocalMod)instance.modManager.installedMods.Find (delegate(Item lmod) {
                                        return ((lmod as LocalMod).id.Equals (id));
                                    }));
                                } catch  (Exception exp) {
                                    Console.WriteLine (exp);
                                }
                            }
                        }
                    } catch  (Exception exp) {
                        Console.WriteLine (exp);
                    }
                    instance.repatch ();
                }

            } else if (instance != null && logger != null && logger.Count > 0) {

                Console.WriteLine (e.ExceptionObject);

                Assembly asm = (e.ExceptionObject as Exception).TargetSite.Module.Assembly;
                Type modClass = (from _modClass in asm.GetTypes ()
                                 where _modClass.InheritsFrom (typeof(BaseMod))
                                 select _modClass).First();

                //no mod classes??
                if (modClass == null) {
                    return;
                }

                foreach (String id in instance.modOrder) {
                    BaseMod mod = null;
                    try {
                        mod = instance.modInstances [id];
                    } catch  (Exception exp) {
                        Console.WriteLine (exp);
                    }
                    if (mod != null) {
                        if (modClass.Equals(mod.GetType())) {
                            String folder = Path.GetDirectoryName (asm.Location);
                            if (File.Exists (folder + Path.DirectorySeparatorChar + "config.json")) {
                                JsonReader reader = new JsonReader ();
                                LocalMod lmod = (LocalMod) reader.Read (File.ReadAllText (folder + Path.DirectorySeparatorChar + "config.json"), typeof(LocalMod));
                                if (!lmod.localInstall)
                                    logger [lmod.localId].logException ((Exception)e.ExceptionObject);
                            }
                        }
                    }
                }
            }
        }
Esempio n. 34
0
        public void Read_ObjectExtraValueAfterClose_ThrowsDeserializationException()
        {
            // input from fail10.json in test suite at http://www.json.org/JSON_checker/
            var input = @"{""Extra value after close"": true} ""misplaced quoted value""";

            var reader = new JsonReader(new DataReaderSettings { AllowTrailingContent=false });

            DeserializationException ex = Assert.Throws<DeserializationException>(
                delegate
                {
                    var actual = reader.Read(input);
                });

            // verify exception is coming from expected position
            // note the reader doesn't see the 2nd object until it is read
            // so the index is after the trailing value
            Assert.Equal(57L, ex.Index);
        }
Esempio n. 35
0
		public static ConfigObject ParseJson (string json)
		{
			var lines = json.Split (new char[] {'\n'});
			// remove lines that start with a dash # character 
			var filtered = from l in lines
				where !(Regex.IsMatch (l, @"^\s*#(.*)"))
				select l;
			
			var filtered_json = string.Join ("\n", filtered);
			
			var json_reader = new JsonReader ();
			dynamic parsed = json_reader.Read (filtered_json);
			// convert the ExpandoObject to ConfigObject before returning
            		var result = ConfigObject.FromExpando(parsed);
			return result;
		}
Esempio n. 36
0
        public void Read_ArrayExtraClose_ThrowsDeserializationException()
        {
            // input from fail8.json in test suite at http://www.json.org/JSON_checker/
            var input = @"[""Extra close""]]";

            var reader = new JsonReader(new DataReaderSettings { AllowTrailingContent=false });

            DeserializationException ex = Assert.Throws<DeserializationException>(
                delegate
                {
                    var actual = reader.Read(input);
                });

            // verify exception is coming from expected position
            Assert.Equal(15L, ex.Index);
        }
Esempio n. 37
0
        public bool tryToFetchModList(Repo repo)
        {
            String modlist = null;
            try {
                WebClientTimeOut client = new WebClientTimeOut ();
                modlist = client.DownloadString (new Uri(repo.url+"modlist"));
            } catch (WebException ex) {
                Console.WriteLine (ex);
                repositories.Remove (repo);
                return false;
            }

            ModListMessage message = null;
            try {
                JsonReader reader = new JsonReader();
                message = reader.Read(modlist, typeof(ModListMessage)) as ModListMessage;
            } catch {
                repositories.Remove (repo);
                return false;
            }

            if (message == null) {
                repositories.Remove (repo);
                return false;
            }

            if (!message.msg.Equals("success")) {
                repositories.Remove (repo);
                return false;
            }

            modsPerRepo.Add (repo, new List<Item>(message.data));
            return true;
        }
Esempio n. 38
0
        // example: https://github.com/numenta/grok-js-ua/blob/master/hello-grok/apiProxy.js
        public void ProcessRequest(HttpContext context)
        {
            dynamic proxyData;
            using (var inputReader = new StreamReader(context.Request.InputStream, context.Request.ContentEncoding))
            {
                //proxyData = Json.Decode(inputReader.ReadToEnd());
                var reader = new JsonFx.Json.JsonReader();
                proxyData = reader.Read(inputReader);
                //var serializer = new DataContractJsonSerializer(typeof(ProxyBody));
                //var proxyData = (ProxyBody)serializer.ReadObject(context.Request.InputStream);
            }

            string endpoint = proxyData.proxy.endpoint;
            bool hasData = ((System.Collections.Generic.IDictionary<String, Object>)proxyData.proxy).ContainsKey("data");

            // write the request data
            if (hasData && proxyData.proxy.method=="GET")
            {
                var ub = new UriBuilder(endpoint);
                var queryString = HttpUtility.ParseQueryString(ub.Query);
                foreach (var dataItem in ((System.Collections.Generic.IDictionary<String, Object>)proxyData.proxy.data))
                {
                    if (dataItem.Value == null) continue;
                    queryString.Add(dataItem.Key, dataItem.Value.ToString());
                }
                ub.Query = queryString.ToString();
                endpoint = ub.Uri.AbsoluteUri;
            }

            var request = WebRequest.CreateHttp(endpoint);
            request.Method = proxyData.proxy.method;

            request.Headers.Add(
                HttpRequestHeader.ContentEncoding,
                "UTF8");
            request.Headers.Add(
                HttpRequestHeader.Authorization,
                GenerateBasicAuthenticationValue(username: proxyData.apiKey, password: string.Empty));

            try
            {
                // write the request data
                if (hasData && proxyData.proxy.method != "GET")
                {
                    using (var dataWriter = new StreamWriter(request.GetRequestStream(), new UTF8Encoding(false)))
                    {
                        var writer = new JsonFx.Json.JsonWriter();
                        writer.Write(proxyData.proxy.data, dataWriter);
                    }
                }

                // read the response

                var response = (HttpWebResponse) request.GetResponse();
                context.Response.StatusCode = (int)HttpStatusCode.OK;
                context.Response.Headers.Add("Content-Encoding", response.ContentEncoding);

                byte[] buffer = new byte[ushort.MaxValue];
                using (var responseStream = response.GetResponseStream())
                {
                    int r;
                    while((r = responseStream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        context.Response.OutputStream.Write(buffer, 0, r);
                    }
                }

                return;
            }
            catch (WebException ex)
            {
                if (ex.Status != WebExceptionStatus.ProtocolError)
                {
                    context.Response.StatusCode = (int)HttpStatusCode.ServiceUnavailable;
                    return;
                }

                var httpResponse = (HttpWebResponse)ex.Response;
                context.Response.StatusCode = (int)httpResponse.StatusCode;
                return;
            }
        }